Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript forEach check all elements true/false

Tags:

javascript

I have a few classes

<div class="adiv"></div>
<div class="adiv"></div>
<div class="adiv cc"></div>
<div class="adiv"></div>
<div class="adiv"></div>

document.querySelectorAll('.adiv').forEach((v, i) => {
    console.log(v.classList.contains('cc'));
});

the result is 2 x false, 1 x true, 2 x false in order. The question is how to write something like below, how to check all together? please no jQuery. Many thanks

if (output is all true) return true else false? 
like image 330
olo Avatar asked Feb 28 '26 10:02

olo


1 Answers

Use Array.prototype.every to check if every element in an array passes a predicate.

[1, 2, 3].every((num) => num > 0); // true

Because you're using document.querySelectorAll, you'll need to convert the array-like object it returns into an actual array.

You can use Array.from for this.

Combined, you get:

allCC =
  Array.from(document.querySelectorAll('.adiv'))
    .every((node) => node.classList.contains('cc'));
like image 70
zzzzBov Avatar answered Mar 02 '26 23:03

zzzzBov



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!