如何删除包含特定文本的div

3

我有一些包含文本和元素的div标签,我想要移除这些div标签,它们看起来像这样:

<div style="font-family:verdana;font-size:12px;">
    Example
    <a href="http://www.example.com" title="hey">example</a>
</div>

有许多像这样的div,我想使用jQuery或JavaScript将它们全部删除


它们有什么共同点吗?它们指向的URL,内联样式...是否有任何方法确保我们获取这些不需要的div? - Juan Ferreras
2个回答

4
如果元素没有共同的类,您可以使用 :containsremove() 方法来删除它。
$("div:contains('Example')").remove()

下面是完整的示例:

$("div:contains('Example')").remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


<div>
  Example
</div>
<div>
  Darren
</div>

如果元素有共同点,您可以使用类选择器。

$(".common-class").remove();

谢谢您的帮助,但是当我写下 $('div:contains('example <a href="http://www.example.com" title="example">example</a>')').remove(); 时,它会出现 SyntaxError: missing ) after argument list 的错误。 - user6373207
它没有被移除,我尝试了这样做:<script> $('div:contains("example <a href="http://www.example.com" title="example">example</a>")').remove(); </script> - user6373207

0

根据达伦的回答,如果你想要更加确定(因为:contains会匹配并删除任何包含单词example的div),你可以确保它是一个带有相同子元素示例的锚点的div,然后返回到父级并将其删除。

如果这不起作用,请粘贴更多的div,以便我们看到一个常见模式并以最安全的方式进行目标定位。

$(document).ready(function(){
  
  $('#remove').click(function(e){

  $("div:contains('Example')").children("a:contains('example')").parent("div:contains('Example')").remove()
})
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="font-family:verdana;font-size:12px;">Example<a href="http://www.example.com" title="hey"> example</a></div>
<div style="font-family:verdana;font-size:12px;">Don't remove<a href="http://www.example.com" title="hey"> example</a></div>
<div style="font-family:verdana;font-size:12px;">Example<a href="http://www.example.com" title="hey"> don't remove</a></div>

<button id="remove">
Remove undesired divs
</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接