JavaScript Code


How to remove a div using JavaScript?


Tutorials using JS

Remove a div using JavaScript

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

Solution

To remove a div element from document using JavaScript, we can use remove() method on the element. Get the div element, and call remove() method.

divElement.remove()

remove() method removes the calling element from the document

Program

1. In the HTML, we have a Click me button and a div. When user clicks on the Click me button, we get the div element by id myDiv and remove it from the document using remove().

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove div from document</h2>
<button id="myBtn">Click me</button>
<div id="myDiv" class="card tile active">About</div>

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

</body>
</html>

Copyright @2022