使用 jQuery 删除文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1571076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove text with jQuery
提问by Dom
Is there a way to remove text that is not wrapped in any tag using jQuery
有没有办法使用jQuery删除未包装在任何标签中的文本
<p>This is some text</p>
This is "unwrapped" text //to be removed
<span>some more text</span>
Thank you for your help
感谢您的帮助
回答by Greg
Using the answer from this question:
使用这个问题的答案:
$(elem)
.contents()
.filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
回答by Kobi
First, you can wrap them with dummy spans:
首先,您可以用虚拟跨度包装它们:
$("body").contents()
.filter(function(){ return this.nodeType != 1; })
.wrap("<span class='orphan'/>");
Now you can remove them easily:
现在您可以轻松删除它们:
$('span.orphan').remove();
回答by sime0n
fwiw..
飞..
<div class="parent-element">
<p>This is some text</p>
This is "unwrapped" text //to be removed
<span>some more text</span>
</div>
via CSS:
通过 CSS:
.parent-element { font-size: 0px; }
.parent-element p { font-size: 12px; }
.parent-element span { font-size: 14px; }
回答by Dom
Wrapping it in a DOM element would mean jQuery can find it:
将它包装在 DOM 元素中意味着 jQuery 可以找到它:
eg:
例如:
var text = 'This is "unwrapped" text';
$("div:contains('" + text + "')").remove();
or just:
要不就:
$('p').next().remove();
回答by it3xl
It's amazing but at the same time the following code doesn't work
这很神奇,但同时以下代码不起作用
$("div.myClass:has(img)").contents().filter(":text").remove();
and the code from the first post works
第一篇文章中的代码有效
$("div.myClass:has(img)")
.contents()
.filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
It's important to remeber! jQuery 1.8.3.
重要的是要记住!jQuery 1.8.3。
And first of all I remember that innerHTML manipulation works much more faster than this approach!
首先,我记得innerHTML 操作的工作速度比这种方法快得多!