有没有办法使用jQuery删除未包含在任何标记中的文本
<p>This is some text</p>
This is "unwrapped" text //to be removed
<span>some more text</span>
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助
Gre*_*reg 47
使用这个问题的答案:
$(elem)
.contents()
.filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
Run Code Online (Sandbox Code Playgroud)
首先,您可以使用虚拟跨度包装它们:
$("body").contents()
.filter(function(){ return this.nodeType != 1; })
.wrap("<span class='orphan'/>");
Run Code Online (Sandbox Code Playgroud)
现在您可以轻松删除它们:
$('span.orphan').remove();
Run Code Online (Sandbox Code Playgroud)