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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With