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:
- How To Get The Last Character Of A String In JavaScript
- Remove The Last Character Of A String In JavaScript
- How To Validate An Email Address In JavaScript
- How To Check If An Input Field Is Empty In JavaScript
- Check If An Input Field Is A Number In JavaScript
- Confirm Password Validation In JavaScript
- How To Print A PDF File Using JavaScript
- Calculate The Number Of Days Between Two Dates In JavaScript
- How To Compare Two Dates In JavaScript
- Calculate Age With Birth Date YYYYMMDD In JavaScript
- How To Append or Add Text To A DIV Using JavaScript
- How To Get The Text Of HTML Element In JavaScript
- How To Change The Text Inside A DIV Element In JavaScript
- Show/Hide Multiple DIVs In JavaScript
- Show A DIV After X Seconds In JavaScript
- Display A JavaScript Variable In An HTML Page
- How To Generate A Random Number In JavaScript
- Bubble Sort In JavaScript
- Insertion Sort In JavaScript
- Selection Sort In JavaScript
- How To Remove A Specific Item From An Array In JavaScript
- Merge Sort In JavaScript
- Round To 2 Decimal Places In JavaScript
- SetInterval() and setTimeout() Methods In JavaScript
- Generate A Unique ID In JavaScript
- Caesar Cipher In JavaScript
- How To Reverse A String In JavaScript
- How To Loop Through A Plain JavaScript Object
- How To Open A URL In A New Tab Using JavaScript?