JavaScript Code


How to hide a div using JavaScript?


Tutorials using JS

Hide a div using JavaScript

In this tutorial, you shall learn how to hide a div element from the document using JavaScript.

Solution

To hide a div element in the document using JavaScript, we can use Element.style.display property. Get the div element, and set its CSS display property with "none".

divElement.style.display = "none";

Program

1. In the HTML code, we have a div element with id myDiv. When user clicks on the Click me button, we get the div element by id myDiv and hide it by setting its CSS display property with none.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Hide div Element</h2>
<button id="myBtn">Click me</button>
<div id="myDiv">A Div</div>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
	//get div element
	const myDiv = document.getElementById("myDiv");
	//hide the div element
    myDiv.style.display = "none";
});
</script>

</body>
</html>

Copyright @2022