Squ*_*Cat 22 css jquery jquery-selectors
我有一种情况,我需要选择某个元素的所有后代,但排除那些容器的子元素,它等于我运行我的选择器的容器的CSS类.
相当复杂的描述.
<div class="container">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element">
<div class="container">
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
在最外面的DIV上运行jQuery .find('.element')将获得所有DIV,甚至是第二个容器内的DIV.这就是我试图避免的.
是否有针对此案例的快速简单的jQuery选择器解决方案?
Cam*_*ike 31
我想你想要使用的是not selector.像这样..
$(".container").not(".container .container")
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用子选择器,让孩子从一个级别深入.哪个会排除嵌套的div.
为了更加明确一点,我想你在使用'find'后会想要使用not选择器.像这样:
$(".container").find(".element").not($(".container .container .element"))
Run Code Online (Sandbox Code Playgroud)
您可以将函数传递给not,因此您可以让该函数查看每个元素匹配的父元素,以查看它是否嵌套在具有相同类的元素内.
removeIfNested = function(index) {
// this is the corrent DOM element
var $this = $(this),
return_value = false;
$.each($this.attr('class').split(/\s+/), function(index) {
if ($this.parents("." + this).length > 0) {
return_value = default_value || true;
}
});
return return_value;
}
$(".container").find(".element").not(removeIfNested);
Run Code Online (Sandbox Code Playgroud)
如果你可以在嵌套容器中添加一个类,那将是理想的,那么它只是:
$(".container").find(".element").not($(".nested .element"))
Run Code Online (Sandbox Code Playgroud)
假设您将类"嵌套"添加到内部容器div中.