用jQuery删除文本

时间:2009-10-15 08:37:47

标签: jquery

有没有办法使用jQuery删除未包含在任何标记中的文本

<p>This is some text</p>

This is "unwrapped" text //to be removed

<span>some more text</span>

感谢您的帮助

5 个答案:

答案 0 :(得分:46)

使用this question的答案:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();

答案 1 :(得分:7)

首先,你可以用虚拟跨度包裹它们:

$("body").contents()
    .filter(function(){ return this.nodeType != 1; })
    .wrap("<span class='orphan'/>");

现在您可以轻松删除它们:

$('span.orphan').remove();

答案 2 :(得分:2)

FWIW ..

<div class="parent-element">
<p>This is some text</p>
This is "unwrapped" text //to be removed
<span>some more text</span>
</div>

通过CSS:

.parent-element { font-size: 0px; }
.parent-element p { font-size: 12px; }
.parent-element span { font-size: 14px; }

答案 3 :(得分:1)

将它包装在DOM元素中意味着jQuery可以找到它:

例如:

var text = 'This is "unwrapped" text';

$("div:contains('" + text + "')").remove();

或只是:

$('p').next().remove();

答案 4 :(得分:1)

令人惊讶,但同时以下代码无法正常工作

$("div.myClass:has(img)").contents().filter(":text").remove();

和第一篇文章的代码

$("div.myClass:has(img)")
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();

记住这一点非常重要! jQuery 1.8.3。

首先我记得innerHTML操作比这种方法更快!