JavaScript Code

How to hide a div using JavaScript?


Tutorials using JS

Problem Statement

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

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