Benos
June 30, 2019, 9:55pm
1
I try to iterate a collection of selectors in the intention of hiding their elements. I tried:
document.querySelectorAll(
"#n-1",
"#n-2",
"#n-3",
).forEach((element)=>{
element.style.display = "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.
igor_g
June 30, 2019, 10:14pm
3
Should be…
document.querySelectorAll("#n-1,#n-2,#n-3")
querySelectorAll() has only one argument.
1 Like
Benos
July 1, 2019, 7:33am
4
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.
document.querySelectorAll(
"#n-1" +
"#n-2" +
"#n-3"
).forEach((element)=>{
element.style.display = "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:
document.querySelectorAll([
'#n-1',
'#n-2',
'#n-3',
])
… 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)=>{ element.style.display = "none"; }
```
Note: Untested due to lack of primary example.
system
Closed
October 1, 2019, 3:51am
9
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.