Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - select an element if children not having a specific class

Tags:

jquery

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?

like image 380
Below the Radar Avatar asked Jan 09 '23 05:01

Below the Radar


1 Answers

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>
like image 62
T.J. Crowder Avatar answered May 23 '23 01:05

T.J. Crowder