3

How can i wrap only the content present inside the span excluding the tags..

Here is the markup what i have...

<span class="foo">
   <span class="bar">+</span>
   lorem ispum lorem ispumlorem ispumlorem ispum
</span>

now this is what i want it to be

<span class="foo">
  <span class="bar">+</span>
  <span class="foobar">lorem ispum lorem ispumlorem ispumlorem ispum</span>
</span>

$('.foo').wrapInner('<span class="foobar"/>') is wrapping the entire inner content.\

thanks in advance..

Green Wizard
  • 3,507
  • 4
  • 18
  • 29
  • possible duplicate of [Wrap text within element](http://stackoverflow.com/questions/13652140/wrap-text-within-element) – wirey00 Apr 21 '14 at 14:22

4 Answers4

3

You have to filter nodes and then wrap. Use .each(). Try this:

$('.foo').each(function() {
    $(this).contents().eq(2).wrap('<span class="foobar"/>');
});

DEMO

Kiran
  • 20,167
  • 11
  • 67
  • 99
2

You can filter out the text nodes and wrap them:

http://jsfiddle.net/dKtD6/

$('.foo').contents().filter(function() {
    return this.nodeType == 3 && $.trim(this.textContent) != '';
}).wrap('<span class="foobar" />');
Jason P
  • 26,984
  • 3
  • 31
  • 45
1

To Wrap the content Inside Tags you can use

 $('.foo').wrapInner('<span class="foobar"></span>');
sshet
  • 1,152
  • 1
  • 6
  • 15
0

You can use nextSibling to get the textNode, then just wrap it

$($('.bar').get(0).nextSibling).wrap('<span class="foobar" />')

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388