Подтвердить что ты не робот

Обтекание текста внутри элемента

Мне нужно обернуть текст внутри 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" />'); 
4b9b3361

Ответ 1

Вы можете сделать это с помощью contents() и . eq()

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

http://jsfiddle.net/qUUbW/

Ответ 2

Как насчет

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

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

Ответ 3

Единый DIV:

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

JSfiddle

Несколько 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" />');
}

JSFiddle

Ответ 4

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

Ответ 5

Мое занятие:

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

Часть $.trim необходима, поскольку вкладки, используемые для кода html с отступом, также являются текстовыми узлами, которые мы должны отфильтровать (например, как вкладка прямо перед <span class="count">)

Смотрите рабочий демо