To show or hide multiple DIVs in JavaScript, you can use the getElementsByClassName() method to select the elements, and then use the ‘style.display’ property to set their visibility.

Here’s an example of how you can hide all DIVs with the class “hideMe”:

var divs = document.getElementsByClassName("hideMe");
for (var i = 0; i < divs.length; i++) {
    divs[i].style.display = "none";
}

And here’s an example of how you can show all DIVs with the class “showMe”:

var divs = document.getElementsByClassName("showMe");
for (var i = 0; i < divs.length; i++) {
    divs[i].style.display = "block";
}

Note: you can use “inline” instead of “block” if you want the DIVs to be displayed inline.

It’s also worth noting that in modern javascript, you could use querySelectorAll instead of getElementsByClassName, this will allow you to use CSS selectors, which are more powerful and familiar to web developers.

document.querySelectorAll('.hideMe').forEach(el => el.style.display = 'none')
document.querySelectorAll('.showMe').forEach(el => el.style.display = 'block')

Also Read:

Categorized in: