Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all children of div have class

I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>

And this would be false as not all children have the same class:

<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

like image 235
Magnus Pilegaard Avatar asked Dec 05 '25 07:12

Magnus Pilegaard


2 Answers

There are multiple ways to do it! Simplest one being:

if($('.parent .child.active').length === $('.parent .child').length){
	//return true
  console.log('true');
}
else{
	//return false
  console.log('false');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>
like image 150
Saurabh Sharma Avatar answered Dec 06 '25 21:12

Saurabh Sharma


Use length comparison or Array.prototype.every.

let parent1 = document.querySelector(".parent1"),
  parent2 = document.querySelector(".parent2");

if (parent1.children.length == parent1.querySelectorAll(".active").length) {
  console.log("All children have the class “active”.");
}

// or

if (Array.from(parent1.children).every(child => child.classList.contains("active"))) {
  console.log("All children have the class “active”.");
}

// similarly, for .parent2:

console.log(parent2.children.length == parent2.querySelectorAll(".active").length);
console.log(Array.from(parent2.children).every(child => child.classList.contains("active")));
<div class="parent1">
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
</div>

<div class="parent2">
  <div class="child active"></div>
  <div class="child"></div>
  <div class="child active"></div>
  <div class="child"></div>
</div>
like image 33
Sebastian Simon Avatar answered Dec 06 '25 20:12

Sebastian Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!