Summary: in this tutorial, you will learn how to use the JavaScript removeChild() method to remove a child node from a parent node.
Introduction to JavaScript removeChild() method #
To remove a child element of a node, you use the removeChild() method:
let childNode = parentNode.removeChild(childNode);The childNode is the child node of the parentNode that you want to remove. If the childNode is not the child node of the parentNode, the method throws an exception.
The removeChild() returns the removed child node from the DOM tree but keeps it in the memory, which can be used later.
If you don’t want to keep the removed child node in the memory, you use the following syntax:
parentNode.removeChild(childNode);The child node will be in the memory until the JavaScript garbage collector destroys it.
JavaScript removeChild() method example #
Suppose you have the following list of items:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>The following example uses the removeChild() to remove the last list item:
let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);How it works:
- First, get the
ulelement with the idmenuby using thegetElementById()method. - Then, remove the last element of the
ulelement by using theremoveChild()method. Themenu.lastElementChildproperty returns the last child element of themenu.
Put it all together.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript removeChild()</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
<script>
let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);
</script>
</body>
</html>Removing all child nodes of an element #
To remove all child nodes of an element, you use the following steps:
- Get the first node of the element using the
firstChildproperty. - Repeatedly removing the child node until there are no child nodes left.
The following code shows how to remove all list items from the menu element:
let menu = document.getElementById('menu');
while (menu.firstChild) {
menu.removeChild(menu.firstChild);}You can remove all child nodes of an element by setting the innerHTML property of the parent node to blank:
let menu = document.getElementById('menu');
menu.innerHTML = '';Summary #
- Use
parentNode.removeChild()to remove a child node from a parent node. - The
parentNode.removeChild()throws an exception if the child node cannot be found in the parent node.
Quiz #
Understanding removeChild() Method
Thank you for your feedback!