How to Hide or Show Element in Javascript
Posted on: February 20, 2021 by Ariessa Norramli
In this article, you will learn how to hide or show an element in Javascript.
Let’s say you have a div element with id ‘theDIV’.
html
<div id="theDIV">
Hi, I'm a DIV element.
</div>
css
#theDIV {
/* Set the width of element to 100% */
width: 100%;
/* Set the top and bottom padding to 50px, right and left padding to 0px*/
padding: 50px 0;
/* Set the text alignment to the center */
text-align: center;
/* Set the background colour to light green */
background-color: lightgreen;
/* Set the top margin to 20px */
margin-top: 20px;
/* Set the bottom margin to 10px */
margin-bottom: 10px;
}
In order to hide or show an element, you can use the document.getElementById()
method and style display property, object.style.display
. In this example, you will be using a button to hide or show a div element.
full html
<!-- A div element with id "theDIV" -->
<div id="theDIV">
Hi, I'm a DIV element.
</div>
<!-- A button element with class "button" that will execute "hideOrShow()" function upon clicking -->
<button class="button" onclick="hideOrShow()">
Click Me
</button>
full css
#theDIV {
/* Set the width of element to 100% */
width: 100%;
/* Set the top and bottom padding to 50px, right and left padding to 0px*/
padding: 50px 0;
/* Set the text alignment to the center */
text-align: center;
/* Set the background colour to light green */
background-color: lightgreen;
/* Set the top margin to 20px */
margin-top: 20px;
/* Set the bottom margin to 10px */
margin-bottom: 10px;
}
.button {
/* Display the element as a block element */
display: block;
/* Center the element */
margin: 0 auto;
}
full javascript
// A function that hides or shows a selected element
function hideOrShow() {
// Select the element with id "theDIV"
var x = document.getElementById("theDIV");
// If selected element is hidden
if (x.style.display === "none") {
// Show the hidden element
x.style.display = "block";
// Else if the selected element is shown
} else {
// Hide the element
x.style.display = "none";
}
}
Show the element
Hide the element
Note: The document.getElementById()
method functions by getting an element whose id matches the supplied string. The style display property, object.style.display
functions by returning or setting the display type of an element.
Share on social media
//