I am looking for a selector only solution, not something using .find()
or other jquery functions.
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
Is there a way to select element only if all of their children have not a specific class?
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
Because :not(".childrenClass")
is not remotely the opposite of :has(".childrenClass")
. :not
tests whether that element doesn't match the selector. :has
tests whether that element's children match the selector.
Is there a way to select element only if all of their children have not a specific class?
Yes, you can combine :not
and :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>
I have to admit that really surprised me, as :has
has a history of not playing nicely with others. Previously, I thought you'd have to use 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With