我不确定该怎么做,所以这是我的难题:
我有关于div的常规文本。但是,在其中添加了一些js span之后。但我想将现有文本包装在span标签中。如何将跨度包装到已经没有跨度的文本中?
Made a fiddle here。
<div class="about">
This text isn't wrapped in an html tag
<span>But this is</span>
</div>
如何通过jquery将常规文本包装到span标签中?
提前谢谢你的帮助。
最佳答案
您可以使用jQuery的.contents
获取文本节点,然后将其包装(如果它们是选中节点的文本节点子级)。
$(".about").contents().filter(function () {
return this.nodeType === 3 && this.parentNode == $(".about").get(0);
}).wrap("<span>");
http://jsfiddle.net/ExplosionPIlls/PXTuD/6/