Home >Web Front-end >JS Tutorial >How Can I Show and Hide DIVs Using JavaScript?
Show/hide 'div' using JavaScript
A common task in web development is to dynamically show or hide elements on the page. This can be accomplished using JavaScript to manipulate the element's style properties.
Hiding a Single Div
To hide a single div with the ID "my_div", use the following code:
document.getElementById("my_div").style.display = "none";
Showing a Hidden Div
To show a hidden div with the ID "my_div", use the following code:
document.getElementById("my_div").style.display = "block";
Toggling Visibility
To toggle the visibility of a div with the ID "my_div", use the following code:
var div = document.getElementById("my_div"); if (div.style.display == "none") { div.style.display = "block"; } else { div.style.display = "none"; }
Using the Visibility Property
Alternatively, the visibility property can be used to hide elements without affecting their layout. To hide a div using visibility, use the following code:
document.getElementById("my_div").style.visibility = "hidden";
To show a hidden div using visibility, use the following code:
document.getElementById("my_div").style.visibility = "visible";
Hiding a Collection of Elements
To hide multiple elements, use a loop to iterate over them and set their display or visibility to "none":
var elements = document.querySelectorAll(".my_class"); for (var i = 0; i < elements.length; i++) { elements[i].style.display = "none"; }
The above is the detailed content of How Can I Show and Hide DIVs Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!