Rob
Rob

Reputation: 6380

Wrap a span element around specific elements and text nodes within a h2 tag

Is it possible to do the following with jQuery so that this:

<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>

Becomes this:

<h2>
    This is a test 
    <span class="wrap">
       <span>i</span>
       mag
       <span>i</span>
       nat
       <span>i</span>
       on   
    </span>
</h2>

So I want the outer span to wrap all the inner spans.

Don't feel this is a duplicate question as I want to just wrap the all the spans and not the text "This is a test".

Upvotes: 3

Views: 232

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 241118

Based on your update, you could filter the contents of the h2 element depending on whether this is a span element or if this.previousSibling is a span element:

$('h2').contents().filter(function () {
  return $(this).is('span') || $(this.previousSibling).is('span');
}).wrapAll('<span class="wrap" />');
.wrap { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>

Alternatively, you could also filter the elements and text nodes and exclude the text nodes with trimmed text that equals 'This is a test':

$('h2').contents().filter(function () {
  return this.textContent.trim() !== 'This is a test';
}).wrapAll('<span class="wrap" />');
.wrap { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>

You could also just exclude the first text node as well:

$('h2').contents().filter(function () {
  return this !== this.parentElement.firstChild;
}).wrapAll('<span class="wrap" />');
.wrap { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>
    This is a test 
    <span>i</span>
    mag
    <span>i</span>
    nat
    <span>i</span>
    on  
</h2>

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167202

You need to use $.wrapAll():

$(function () {
  $("h2 span").wrapAll('<span class="wrap" />');
});
.wrap {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
  This is a test 
  <span>Test</span>
  <span>Test</span>
  <span>Test</span>   
</h2>

Upvotes: 4

Related Questions