我正在寻找仅选择器的解决方案,而不是使用 .find()
或其他 jquery 函数的解决方案。
我想知道为什么如果我这样做$('.parentClass:has(".childrenClass")')
,如果它们的子元素之一具有.childrenClass
,它会返回元素
但是如果我这样做 $('.parentClass:not(".childrenClass")')
它会返回所有元素,即使它们的子元素之一具有 .childrenClass
有没有办法仅在所有子元素都没有特定类的情况下才选择元素?
最佳答案
I wander why if I do $('.parentClass:has(".childrenClass")'), it returns elements if one of their children has .childrenClass but if I do $('.parentClass:not(".childrenClass")') it returns all elements even if one of their children has .childrenClass
因为 :not(".childrenClass")
与 :has(".childrenClass")
并不完全相反。 :not
测试该元素是否与选择器不匹配。 :has
测试该元素的子元素是否与选择器匹配。
Is there a way to select element only if all of their children have not a specific class?
是的,您可以组合 :not
和 :has
:
$(".parentClass:not(:has(.childrenClass))").css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentClass">
Should match, no children with childrenClass
</div>
<div class="parentClass">
Should match,
<span>no children with childrenClass</span>
</div>
<div class="parentClass">
Shouldn't match,
<span class="childrenClass">has children with childrenClass</span>
</div>
<div class="parentClass">
Shouldn't match,
<span class="childrenClass">has children</span>
<span class="childrenClass">with childrenClass</span>
</div>
我必须承认,这确实让我感到惊讶,因为 :has
有与他人相处不好的历史。以前,我认为你必须使用 filter
:
$(".parentClass").filter(function() {
return $(this).find(".childrenClass").length == 0;
}).css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentClass">
Should match, no children with childrenClass
</div>
<div class="parentClass">
Should match,
<span>no children with childrenClass</span>
</div>
<div class="parentClass">
Shouldn't match,
<span class="childrenClass">has children with childrenClass</span>
</div>
<div class="parentClass">
Shouldn't match,
<span class="childrenClass">has children</span>
<span class="childrenClass">with childrenClass</span>
</div>
关于jquery - 如果子元素没有特定的类,则选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647994/