我有一些包含文本和元素的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将它们全部删除
我有一些包含文本和元素的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将它们全部删除
:contains
和 remove()
方法来删除它。$("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();
根据达伦的回答,如果你想要更加确定(因为: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>