In this tutorial we will learn How to Hide and Show div using JavaScript. HTML DOM Element style property and if else statement can be used to hide and show div on click, with the same button.
Table of Contents
style property
style property returns the style properties and values of HTML element.
In this example style property is used to hide and show div tag by changing it's display property.
HTML Code
HTML Code is given below, in this code we have a div and a button with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>Hide and Show div JavaScript</title>
<style>
.main
{
background-color: orange;
padding: 50px 10px;
margin: 20px 0px;
}
</style>
</head>
<body>
<div id="div" class="main">This is main div.</div>
<button onclick="hideShow()">Hide and Show</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function hideShow() will hide and show the div element on click of a button.
This is done using single button, that is why we have used if else statement.
The if else statement will decide whether to hide the div or to display it. The decision is made based on the value of variable named display.
The value of display variable is changed on every click.
getElementById() method is used to select the div using it's id.
<script>
var div = document.getElementById('div');
var display = 0;
function hideShow()
{
if(display == 1)
{
div.style.display = 'block';
display = 0;
}
else
{
div.style.display = 'none';
display = 1;
}
}
</script>
We can also use getElementsByClassName() method to select the div and then hide it or show it.
<script>
var div = document.getElementsByClassName('main');
var display = 0;
function hideShow()
{
if(display == 1)
{
div[0].style.display = 'block';
display = 0;
}
else
{
div[0].style.display = 'none';
display = 1;
}
}
</script>
getElementsByClassName() method returns collection of HTML elements with same class name. That is why we use index value while selecting a specific HTML element.
div[0] will select the first div, while div[1] will select the second div and so on.
If there are more than one divs with same class name then it is recommended to use getElementById() method.
Demo
Video Tutorial
Watch video tutorial on how to Hide and Show div with JavaScript.