grizzly
grizzly

Reputation: 608

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?

Upvotes: 2

Views: 76

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115272

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>

FYI : Where >(children selector) is using to check the direct child otherwise it may check for nested, so you can avoid if it's not a problem.

Upvotes: 0

Jai
Jai

Reputation: 74738

You can use .filter():

var divs = $('.A.B').filter(function(){
   return $(this).children('span.D').length === 0;
});

console.log(divs.text());
<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>

Upvotes: 2

Related Questions