grizzly grizzly - 4 months ago 18
jQuery Question

Select list of element having a child element without a specific class

<div class="wrapper">
<div class="A B">
<span class="C">needed</span>
</div>
<div class="A B">
<span class="D">not needed</span>
</div>
<div class="A B">
<span class="E">needed</span>
</div>
</div>


I need all the div elements those do not have a child span with class "D". Is there a jQuery selector for this operation?

Answer

You can use combination of :has() and :not() pseudo-class selectors. Where :has() can be used for checking the selected element contains any certain element and then filter out them using :not() selector. Although filter() method can be use as in @Jai answer.

$('.A.B:not(:has(>.D))').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="A B">
    <span class="C">needed</span>
  </div>
  <div class="A B">
    <span class="D">not needed</span>
  </div>
  <div class="A B">
    <span class="E">needed</span>
  </div>
</div>