有没有办法清空一个div,只留下带有特定类名的元素?或者,有没有办法删除div中的所有元素,只留下具有指定类的元素?
发布于 2009-08-11 21:12:32
这应该能起到作用:
$('#theDiv').find('*').not('.className').remove();
示例标记:
<div id="theDiv">
<p>this will be removed</p>
<p class="className">this will stay</p>
</div>
发布于 2015-06-18 01:35:50
以下是仅使用jQuery选择器的另一个选项:
$("#theDiv *:not('.className')").remove();
像这样的方法和上面的方法的问题是,如果有任何子元素,它们也会被删除,例如:
<div id="theDiv">
<p>this will be removed</p>
<p class="className"><strong>this will also be removed :(</strong></p>
</div>
this也将被删除:(文本也将被删除,因为它与通配符*匹配,并且没有className类。为了解决这个问题,我们只想过滤父级的直接子级,例如:
$("#theDiv > *:not('.className')").remove();
发布于 2009-08-11 21:12:28
@Marve的方法可能更好,但这里有另一种方法(使用filter):
$("#yourDiv").html($('#yourDiv').filter('.IWantThisClass, .IWantThisToo').html());
https://stackoverflow.com/questions/1262930
复制相似问题