JavaScript - How to show and hide div by a button click

Here's how to toggle a div element display by using button onclick event

Posted on April 29, 2021


To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element that will change the display attribute of the <div> from the default value (which is block) to none.

For example, suppose you have an HTML <body> element as follows:

<body>
  <div id="first">This is the FIRST div</div>
  <div id="second">This is the SECOND div</div>
  <div id="third">This is the THIRD div</div>
  <button id="toggle">Hide THIRD div</button>
</body>

The <button> element above will hide or show the <div id="third"> element on click, so let’s add the onclick event listener to the <button> as follows:

const targetDiv = document.getElementById("third");
const btn = document.getElementById("toggle");
btn.onclick = function () {
  if (targetDiv.style.display !== "none") {
    targetDiv.style.display = "none";
  } else {
    targetDiv.style.display = "block";
  }
};

The HTML will be rendered as if the <div> element never existed by setting the display attribute to none. When you click the <button> element again, the display attribute will be set back to block, so the <div> will be rendered back in the HTML page.

Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more