Removing an HTML element using JavaScript means deleting an element from the Document Object Model (DOM). This is useful when you want to dynamically update a webpage based on user actions, events, or application requirements.
JavaScript provides multiple ways to remove elements from the DOM.
Approach 1: Using removeChild() Method
The removeChild() method removes a specified child element from its parent element. To use this method, you first select the element to remove and then call removeChild() on its parent.
Syntax:
parentElement.removeChild(childElement);Example: In this example, clicking the button removes the <div> element from the page using the removeChild() method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Remove HTML Element</title>
<style>
#element {
width: 200px;
height: 100px;
margin: 20px auto;
padding: 20px;
background-color: green;
color: white;
}
</style>
</head>
<body style="text-align: center;">
<h2>Remove an HTML Element</h2>
<p>Click the button to remove the element.</p>
<div id="element">
This is a div element.
</div>
<button onclick="removeElement()">
Remove Element
</button>
<p id="message"></p>
<script>
function removeElement() {
const element =
document.getElementById("element");
const message =
document.getElementById("message");
if (element) {
element.parentNode.removeChild(element);
message.textContent = "Element removed successfully.";
}
}
</script>
</body>
</html>
Output:
Approach 2: Using remove() Method
The remove() method directly removes an element from the DOM. Unlike removeChild(), you do not need to explicitly select the parent element.
This is generally a simpler and more modern approach.
Syntax:
element.remove();Example: In this example, clicking the button removes the <div> element directly using the remove() method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Remove HTML Element</title>
<style>
#element {
width: 200px;
height: 100px;
margin: 20px auto;
padding: 20px;
background-color: green;
color: white;
}
</style>
</head>
<body style="text-align: center;">
<h2>Remove an HTML Element</h2>
<p>Click the button to remove the element.</p>
<div id="element">
This is a div element.
</div>
<button onclick="removeElement()">
Remove Element
</button>
<p id="message"></p>
<script>
function removeElement() {
const element =
document.getElementById("element");
const message =
document.getElementById("message");
if (element) {
element.remove();
message.textContent = "Element removed successfully.";
}
}
</script>
</body>
</html>
Output: