How can I hide all the DIVs whose IDs are in myArray? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I hide all the DIVs whose IDs are in myArray?

I have this on my HTML page: <div id="D1"></div> <div id="D2"></div> <div id="D3"></div> I have a variable in Javascript like this: var myArray = ["D1", "D3"]; I know I can hide a div using the DOM document.getElementById().style.display = “none”, but it only hides the one div with that specific ID. How can I hide all the DIVs whose IDs are in myArray? Thanks in advance!

7th Dec 2018, 10:58 PM
Daryl
Daryl - avatar
3 Answers
+ 6
document.querySelectorAll('#'+myArray.join(', #')).forEach(e => e.style.display = "none");
7th Dec 2018, 11:49 PM
visph
visph - avatar
+ 1
I guess it's because I'm new, but all that seem very foreign to me.. I did eventually figure it out: var myArray = ["D1", "D3"]; for (i = 0; i < myArray.length; i++) { document.getElementById(myArray[i]).style.display = "none"; } It just didn't work previously because I declared the myArray variable outside of the function. Thanks guys!
8th Dec 2018, 1:03 AM
Daryl
Daryl - avatar
0
Using myArray.forEach( myArrayparam =>{ myArrayparam.style... });
7th Dec 2018, 11:14 PM
Something Just Like This
Something Just Like This - avatar