We can use JavaScript to show a div by combing the getElementById() method along with the Style display property.

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

Let’s say we have the following html:

This is a hidden div that we can show with JavaScript

Next, we want to show 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.

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

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

Using JavaScript to Show a Div With a Click

We can use JavaScript to show 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 show a hidden div #div1. The div will just be a greenish box, that will have its display property set to “none” to start.

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

Here is the HTML code:


Show hidden div
Hide 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 “block”, which will show the div.

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

Here is the JavaScript code:

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

The final code and output for this example of using JavaScript to show a div with a click is below:

Code Output:

Show hidden div
Hide div

Full Code:

Show hidden div
Hide div

Hopefully this article has been useful for you to understand how to use JavaScript to show a div.

Categorized in:

JavaScript,

Last Update: February 26, 2024