bluetinman bluetinman - 5 months ago 11
jQuery Question

Add class if child element not present

If this works when a class is present...

$('.priority').children('.no-priority').addClass('normal');


How would I add a class if the child class .no-priority is missing?

Tried code below which does not work

if (!$('.priority').children('.no-priority')) {
$('.priority').addClass('prioritised');
}


Neither does

$('.priority').not('.no-priority').addClass('prioritised');

Answer

You can use :not(), :has()

$(".priority:not(:has(.no-priority))").addClass("normal")
.normal {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="priority">
  <div class="does-not-have-no-priority">
    does not have .no-priority
  </div>
</div>

<div class="priority">
  <div class="no-priority">
    has .no-priority
  </div>
</div>

alternatively, using .querySelectorAll(), spread element, for..of loop

for (let el of [...document.querySelectorAll(".priority")]) {
  if (!el.querySelector(".no-priority")) el.classList.add("normal")
}
.normal {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="priority">
  <div class="does-not-have-no-priority">
    does not have .no-priority
  </div>
</div>

<div class="priority">
  <div class="no-priority">
    has .no-priority
  </div>
</div>

Comments