Remove All Child Nodes

Summary: in this tutorial, you will learn how to remove all child nodes of a node using the JavaScript DOM methods.

To remove all child nodes of a node, you use the following steps:

  • First, select the first child node (firstChild) and remove it using the removeChild() method. Once the first child node is removed, the next child node will automatically become the first child node.
  • Second, repeat the first steps until there is no remaining child node.

The following removeAllChildNodes() function removes all the child nodes of a node:

function removeAllChildNodes(parent) {
    while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
    }
}Code language: PHP (php)

Suppose that you have the following HTML document:

<html lang="en">
<head>
  <title>Remove All Child Nodes</title>
</head>
<body>
  <div id="container">
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
  </div>
</body>
</html>Code language: HTML, XML (xml)

The following script will remove all child nodes of the <div> with the id container:

function removeAllChildNodes(parent) {
    while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
    }
}
const container = document.querySelector('#container');
removeAllChildNodes(container);Code language: PHP (php)

Caution: innerHTML

The following code also removes all child nodes of a node:

parent.innerHTML = '';Code language: PHP (php)

However, it is not recommended because it doesn’t remove the event handlers of the child nodes, which might cause a memory leak.

Was this tutorial helpful ?