El-Jus
El-Jus

Reputation: 61

Find element that has no direct children with specific class

In a page of HTML elements, I am trying to find a parent element with class .dmc that does not contain a direct child element with a specific class .dynamic, using JQuery.

I have tried:

$('.dmc:not(:has(.dynamic))')

However this checks all descendants, and I only want to check the first level of descendants.

I think there is a very simple answer, but I can't quite come up with it. Any help appreciated!

Upvotes: 1

Views: 357

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074058

Since :has is already jQuery-specific, you could use an unrooted >, which jQuery's Sizzle selector engine seems to support:

$(".dmc:not(:has(> .dynamic))").addClass("green");
// --------------^

$(".dmc:not(:has(> .dynamic))").addClass("green");
.green {
  color: green;
  font-weight: bold;
}
<div class="dmc">1</div>
<div class="dmc">2
  <div class="dynamic">dynamic</div>
</div>
<div class="dmc">3</div>
<div class="dmc">4
  <div class="dynamic">dynamic</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

But I'd be slightly worried about it, and would probably go for filter instead:

$(".dmc").filter(function() {
  return $(this).children(".dynamic").length == 0;
}).addClass("green");

$(".dmc").filter(function() {
  return $(this).children(".dynamic").length == 0;
}).addClass("green");
.green {
  color: green;
  font-weight: bold;
}
<div class="dmc">1</div>
<div class="dmc">2
  <div class="dynamic">dynamic</div>
</div>
<div class="dmc">3</div>
<div class="dmc">4
  <div class="dynamic">dynamic</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 3

Related Questions