Home > Web Front-end > JS Tutorial > How Can I Show and Hide DIVs Using JavaScript?

How Can I Show and Hide DIVs Using JavaScript?

Linda Hamilton
Release: 2024-12-02 16:22:15
Original
831 people have browsed it

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";
Copy after login

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";
Copy after login

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";
}
Copy after login

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";
Copy after login

To show a hidden div using visibility, use the following code:

document.getElementById("my_div").style.visibility = "visible";
Copy after login

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";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template