Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select elements that do not contain a class [duplicate]

I would like to select all elements with the .hi class, that do not contain the .image class.

<div class="hi">
  <div class="hue">
    <div class="image">
       456
    </div>
  </div>
</div>
<div class="hi">
  <div class="hue">
    <div class="image">
        123
    </div>
  </div>
</div>
<div class="hi">
  <div class="hue">
    here
  </div>
</div>

I tried something like this but it didn't work:

console.log($('.hi').find('.hue > :not(.image')));
like image 629
George Morris Avatar asked Aug 31 '25 02:08

George Morris


1 Answers

To do it just with a selector, you'd use :not with :has:

$(".hi:not(:has(.image))")
// or to be more specific:
$(".hi:not(:has(.hue > .image))")

Note that :has is jQuery-specific.

To do it with filter, you could use find in the callback:

$(".hi").filter(function() { return $(this).find(".image").length == 0; })
// or to be more specific:
$(".hi").filter(function() { return $(this).find(".hue > .image").length == 0; })
like image 89
T.J. Crowder Avatar answered Sep 02 '25 16:09

T.J. Crowder