JavaScript removeChild

Created with Sketch.

JavaScript removeChild

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);

Code language: JavaScript (javascript)

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);

Code language: CSS (css)

The child node will be in the memory until it is destroyed by the JavaScript garbage collector.

JavaScript removeChild() example

Suppose you have the following list of items:

<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>

Code language: HTML, XML (xml)

The following example uses the removeChild() to remove the last list item:

let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);

Code language: JavaScript (javascript)

How it works:

  • First, get the ul element with the id menu by using the getElementById() method.
  • Then, remove the last element of the ul element by using the removeChild() method. The menu.lastElementChild property returns the last child element of the menu.

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>

Code language: HTML, XML (xml)

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 firstChild property.
  • Repeatedly removing the child node until there are no child nodes left.

The following code shows how to remove all list items of the menu element:

let menu = document.getElementById('menu');
while (menu.firstChild) {
menu.removeChild(menu.firstChild);
}

Code language: JavaScript (javascript)

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 = '';

Code language: JavaScript (javascript)

Summary

  • Use parentNode.removeChild() to remove a child node of a parent node.
  • The parentNode.removeChild() throws an exception if the child node cannot be found in the parent node.

Leave a Reply

Your email address will not be published. Required fields are marked *