开发者

Remove text with jQuery

开发者 https://www.devze.com 2022-12-08 19:29 出处:网络
Is there a way to remove text that is not wrapped in any tag using jQuery <p>This is some text</p>

Is there a way to remove text that is not wrapped in any tag using jQuery

<p>This is some text</p>

Th开发者_C百科is is "unwrapped" text //to be removed

<span>some more text</span>

Thank you for your help


Using the answer from this question:

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


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();


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:

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


Wrapping it in a DOM element would mean jQuery can find it:

eg:

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

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

or just:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号