Ответ 1
Вы можете сделать это с помощью contents() и . eq()
$('.item').each(function(i, v) {
$(v).contents().eq(2).wrap('<span class="new"/>')
});
Мне нужно обернуть текст внутри div с помощью 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>
Пробовал это, но он действительно не работал...
$('.item').text().wrap('<span class="new" />');
Вы можете сделать это с помощью contents() и . eq()
$('.item').each(function(i, v) {
$(v).contents().eq(2).wrap('<span class="new"/>')
});
Как насчет
$('.item').contents().filter(function(){
return this.nodeType == 3 && $.trim(this.nodeValue).length;
}).wrap('<span class="new" />');
Единый DIV:
var txt = $('.count')[0].nextSibling;
$(txt).wrap('<span class="new" />');
Несколько DIV:
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" />');
}
$('.item').html($('<span class="new">').text($(".item").text()))
Мое занятие:
$('.item').contents().each(function() {
if (this.nodeType == 3 && $.trim(this.nodeValue) != '') {
$(this).wrap('<span class="textwrapped"></span>');
}
});
Часть $.trim
необходима, поскольку вкладки, используемые для кода html с отступом, также являются текстовыми узлами, которые мы должны отфильтровать (например, как вкладка прямо перед <span class="count">
)
Смотрите рабочий демо