16

I need to wrap text inside a div with a span.

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

<div class="item">
   <span class="count"></span>
   Text that needs to be wrapped.
</div>

Tried this but it did not really work...

$('.item').text().wrap('<span class="new" />'); 
santa
  • 12,234
  • 49
  • 155
  • 255

6 Answers6

25

You can do it using contents() and .eq()

$('.item').each(function(i, v) {
    $(v).contents().eq(2).wrap('<span class="new"/>')
});​

http://jsfiddle.net/qUUbW/

wirey00
  • 33,517
  • 7
  • 54
  • 65
12

How about

$('.item').contents().filter(function(){
    return this.nodeType == 3 && $.trim(this.nodeValue).length;
}).wrap('<span class="new" />');

http://jsfiddle.net/mowglisanu/x5eFp/3/

Musa
  • 96,336
  • 17
  • 118
  • 137
  • I was about to post almost the same thing, you can optimize it by replacing `$.trim($(this).text()).length` for `$.trim(this.nodeValue) != ''` – Nelson Nov 30 '12 at 20:11
  • I noticed that   in the div was also wrapped... while @wirey's solution did not. Thanks for the help. – santa Nov 30 '12 at 20:19
4

Single DIV:

var txt = $('.count')[0].nextSibling;
$(txt).wrap('<span class="new" />');

JSfiddle

Multiple DIVs:

var markers = document.querySelectorAll('.count'),
    l = markers.length,
    i, txt;

for (i = l - 1; i >= 0; i--) {
    txt = markers[i].nextSibling;
    $(txt).wrap('<span class="new" />');
}

JSFiddle

spliter
  • 12,321
  • 4
  • 33
  • 36
  • Sorry, my example had a single div, there could be multiple: http://jsfiddle.net/TELV6/1/ – santa Nov 30 '12 at 20:03
3

if you need to wrap text content inside an element use wrapInner

https://api.jquery.com/wrapInner/

example html

<div class="item">contents inside needs to be wrapped</div>`
// jQuery
$('.item').wrapInner('<span></span>')
shakee93
  • 4,976
  • 2
  • 28
  • 32
2

My take on this:

$('.item').contents().each(function() {
    if (this.nodeType == 3 && $.trim(this.nodeValue) != '') {
       $(this).wrap('<span class="textwrapped"></span>');
    }
});

The $.trim part is needed as tabs used to indent html code are also text nodes that we have to filter out (eg. as the tab right before <span class="count"> )

See working demo

Nelson
  • 49,283
  • 8
  • 68
  • 81
1
$('.item').html($('<span class="new">').text($(".item").text()))
Dan
  • 12,409
  • 3
  • 50
  • 87