How to toggle between hiding and showing an element with JavaScript?

To toggle between hiding and showing an element with JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   button {
      padding: 10px;
      border: none;
      background-color: rgb(51, 51, 192);
      color: white;
      font-size: 18px;
   .div-visible {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: rgb(210, 230, 173);
      margin-top: 20px;
      font-size: 18px;
      font-weight: 500;
<h1>Toggle hide and show example</h1>
<button class="toggleDisplay">Hide Div</button>
<h2>Click on the above button to hide the div below</h2>
<div class="div-visible">
This is a div element
   document .querySelector(".toggleDisplay") .addEventListener("click", toggleDivDisplay);
   function toggleDivDisplay() {
      var x = document.querySelector(".div-visible");
      if ( === "none") { = "block";
      } else { = "none";


The above code will produce the following output −

On clicking the “Hide Div” button −