We can hide a div in JavaScript easily by combing the getElementById() method along with the Style display property.

document.getElementById("div1").style.display = "none";

Let’s say we have the following html:

This is a div that we can hide with JavaScript

Next, we want to hide the div, so we will use the element’s display property. We do this simply by getting the id of the div and then changing its display property to “none”.

document.getElementById("div1").style.display = "none";

Note that we can also hide a div easily using jQuery with the hide() method.

Hiding a Div in JavaScript With a Click

We can use JavaScript to hide a div very easily by combining the display property with an onclick event.

Let’s say that we have the following HTML where we want to give the user the ability to hide a div #div1. The div will just be a greenish box with set dimensions.

We will also provide a button to let the user be able to show the div so they can show and hide the div as much as they want.

Here is the HTML code:


Hide div above
Show hidden div

In the JavaScript code, we will add an onclick event to a button that will run a function we will create. In the function, we will simply change the display property of the div to “none”, which will hide the div.

We will also have another function that will let the user show the div.

Here is the JavaScript code:

function hideDiv(){
  document.getElementById("div1").style.display = "none";
};
function showDiv(){
  document.getElementById("div1").style.display = "block";
}; 

The final code and output for this example of hiding a div in JavaScript with a click is below:

Code Output:

Hide div above
Show hidden div

Full Code:

Hide div above
Show hidden div




Hopefully this article has been useful for you to understand how to hide a div in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024