在元素中包装文本

我需要在带有span的div中包装文本。

Text that needs to be wrapped.
Text that needs to be wrapped.
Text that needs to be wrapped.

试过这个,但它没有真正起作用……

 $('.item').text().wrap(''); 

你可以使用contents()和.eq()来做到这一点

 $('.item').each(function(i, v) { $(v).contents().eq(2).wrap('') });​ 

http://jsfiddle.net/qUUbW/

怎么样

 $('.item').contents().filter(function(){ return this.nodeType == 3 && $.trim(this.nodeValue).length; }).wrap(''); 

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

单DIV

 var txt = $('.count')[0].nextSibling; $(txt).wrap(''); 

的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(''); } 

的jsfiddle

 $('.item').html($('').text($(".item").text())) 

我对此的看法:

 $('.item').contents().each(function() { if (this.nodeType == 3 && $.trim(this.nodeValue) != '') { $(this).wrap(''); } }); 

$.trim部分是必需的,因为用于缩进html代码的标签也是我们必须过滤掉的文本节点(例如,作为之前的标签)

看工作演示