Reputation: 12512
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
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
Reputation: 50643
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
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
Reputation: 33661
You can do it using contents() and .eq()
$('.item').each(function(i, v) {
$(v).contents().eq(2).wrap('<span class="new"/>')
});
Upvotes: 25
Reputation: 12599
Single DIV:
var txt = $('.count')[0].nextSibling;
$(txt).wrap('<span class="new" />');
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" />');
}
Upvotes: 4