Deleting an HTML element in JavaScript can be done using the remove()
method:
const el = document.getElementById('elementToRemove');
el.remove();
Deleting an HTML element in JavaScript can be done using the remove()
method or by accessing the parent node and using the removeChild()
method. Below are the most common approaches:
remove()
MethodThe remove()
method is straightforward and allows you to directly remove the element from the DOM.
<!DOCTYPE html>
<html>
<head>
<title>Remove Element Example</title>
</head>
<body>
<div id="elementToRemove">This element will be removed.</div>
<button onclick="removeElement()">Remove Element</button>
<script>
function removeElement() {
var element = document.getElementById('elementToRemove');
if (element) {
element.remove();
}
}
</script>
</body>
</html>
parentNode.removeChild()
MethodThis method involves removing a child element from its parent node.
<!DOCTYPE html>
<html>
<head>
<title>Remove Element Example</title>
</head>
<body>
<div id="elementToRemove">This element will be removed.</div>
<button onclick="removeElement()">Remove Element</button>
<script>
function removeElement() {
var element = document.getElementById('elementToRemove');
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
}
</script>
</body>
</html>
innerHTML
PropertyIn some cases, you might want to clear all child elements of a parent element. This can be done with the innerHTML
property.
<!DOCTYPE html>
<html>
<head>
<title>Remove Element Example</title>
</head>
<body>
<div id="container">
<div id="elementToRemove">This element will be removed.</div>
</div>
<button onclick="clearContainer()">Clear Container</button>
<script>
function clearContainer() {
var container = document.getElementById('container');
container.innerHTML = ''; // This will remove all child nodes within the container
}
</script>
</body>
</html>
remove()
method is widely supported in modern browsers but may not work in very old browsers like Internet Explorer.removeChild()
ensures compatibility with older browsers, but requires that you have a reference to the parent node.innerHTML
to clear content is efficient but will remove all children and may have performance implications if the DOM is very large.Choose the method that best suits your application's requirements and browser support needs.