JavaScript HTML DOM Elements (Nodes) | Removing Existing HTML Elements

Removing Existing HTML Elements

To remove an HTML element, you must know the parent of the element:

Example


<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p2");
parent.removeChild(child);
</script>

</body>
</html>

Output

This is a paragraph.


The method node.remove() is implemented in the DOM 4 specification.
But because of poor browser support, you should not use it.

Example Explained 

This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent = document.getElementById("div1");
Find the <p> element with id="p1":
var child = document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);
It would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent.
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child = document.getElementById("p1");
child.parentNode.removeChild(child);

No comments:

Post a Comment