How to Hide and Show DIV Element using Javascript

In this tutorial, you will learn how to hide and show div element using javascript. The div element is generally used as a container for other elements.  Since elements are in a container, it becomes extremely easy to position them accordingly.

If you are planning to toggle the visibility of certain elements with the help of javascript, then you might end up writing a good amount of code depending upon the number of the elements.

But if those elements are child elements of a div element, then a few lines of code will be enough to toggle their visibility. In javascript, each DOM element has a style property.  This style property is used to get or set different styles of an element using CSS properties.

The display property is one of those CSS properties and we are going to take advantage of this property to accomplish our goal.

In the following example, we have a button element and a div element. Upon click of a button, we will toggle the visibility of the div element.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 2 elements in the HTML file (button and div).
  • The button element has “Toggle” as innerText.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>

<body>

    <button>Toggle</button>
    <div></div>

    <script src="script.js"></script>
</body>

</html>
div {
  height: 250px;
  width: 250px;
  background-color: red;
  margin-top: 20px;
}

Javascript

  • We have selected button and div elements using the document.querySelector() method and stored them in the btn and div variables respectively.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are using if statement to verify whether the display property of the div element is set to “none” or not.
  • If it is “none”, then we will set it to “block” and if it is “block”, then we will set it to “none”.
  • The value of "none" means the div element is not visible and the value of "block" means the div element is visible.
let btn = document.querySelector("button");
let div = document.querySelector("div");

btn.addEventListener("click", () => {
  if (div.style.display === "none") {
    div.style.display = "block";
  } else {
    div.style.display = "none";
  }
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •