Targeting all array items and run on them with forEach() method

I try to iterate a collection of selectors in the intention of hiding their elements. I tried:

).forEach((element)=>{ = "none";

This code keeps failing in the error that "#n-1", is not a valid selector.
What’s wrong?

In what browser? #n-1 is not invalid as a selector.

Should be…


querySelectorAll() has only one argument.

1 Like

I use latest Google chrome.

@igor_g given the actual ,is way longer, how could I use a multiline list?

You can use the addition symbol to use a multiline list.

    "#n-1" +
    "#n-2" +
).forEach((element)=>{ = "none";
1 Like

still needs the commas, or else you’re making a massive selector.

Or you might pass an array of the selectors, which will get stringified by joining it with commas anyway:


… although you might still want to explicitly join(',') it (or coerce it to a string at any rate) for the sake of readability and type checking.

1 Like

Should also be able to create a collection for each query and then combine them into an array with the new ES6 ‘spread/rest’ designation.

For example:

let n1 = document.querySelectorAll('#n-1');
let n2 = document.querySelectorAll('#n-2');
let n3 = document.querySelectorAll('#n-3');
// etc. as needed
let nAll = [...n1, ...n2, ...n3];
nAll.forEach((element)=>{ = "none"; }

Note: Untested due to lack of primary example.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.