Jquery - select element if children not having a specific class
I'm looking for a selector-only solution, not something using .find()
or other jquery functions.
I am wandering why, if I do $('.parentClass:has(".childrenClass")')
, it returns items 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 an element only if all of their children don't have a specific class?
source to share
I am wandering why if I do $ ('. ParentClass: has (". ChildrenClass")') it returns items 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")
not remotely opposite :has(".childrenClass")
. :not
checks if a selector matches this element . :has
checks if this element matches a child selector.
Is there a way to select an element only if all of their children don't have 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 it really surprised me as it :has
has a history of not playing very well with others. I used to think that you would 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>
source to share