olo
olo

Reputation: 5271

javascript forEach check all elements true/false

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? 

Upvotes: 3

Views: 2801

Answers (2)

Sebastian Simon
Sebastian Simon

Reputation: 19545

The Array.from().every() approach would work generally. There’s another quite elegant way in this case, though:

!document.querySelectorAll(".adiv:not(.cc)").length

This returns the negated length (true for 0, false otherwise) of all elements where the class adiv appears without the class cc.

Another way:

document.querySelectorAll(".adiv").length == document.querySelectorAll(".adiv.cc").length

This compares the number of .adiv to the number of elements with both classes.

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179284

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'));

Upvotes: 6

Related Questions