santa
santa

Reputation: 12512

Wrap text within element

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" />'); 

Upvotes: 16

Views: 29770

Answers (6)

shakee93
shakee93

Reputation: 5426

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>')

Upvotes: 3

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

Upvotes: 2

Musa
Musa

Reputation: 97727

How about

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

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

Upvotes: 12

wirey00
wirey00

Reputation: 33661

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/

Upvotes: 25

spliter
spliter

Reputation: 12599

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

Upvotes: 4

Dan
Dan

Reputation: 13210

$('.item').html($('<span class="new">').text($(".item").text()))

Upvotes: 1

Related Questions