How To Toggle Between Hiding And Showing an Element

Toggle between hiding and showing an element with JavaScript

Toggle (Hide/Show) an Element

Step 1) Add HTML:

Example

<button onclick="myFunction()">Click Me</button>

<div id="myDIV">
  This is my DIV element.
</div>

Step 2) Add JavaScript:

Example

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
Try it Yourself »

Tip: For more information about Display and Visibility, read our CSS Display Tutorial.