How to remove all children of an element using JavaScript

To remove all child nodes of an element, you can use the element's removeChild() method along with the lastChild property.

The removeChild() method removes the given node from the specified element. It returns the removed node as a Node object, or null if the node is no longer available.

Here is an example code snippet:

const removeChilds = (parent) => {
    while (parent.lastChild) {
        parent.removeChild(parent.lastChild);
    }
};

// select target target 
const body = document.querySelector('body');

// remove all child nodes
removeChilds(body);

The removeChilds() method does the following:

  1. Select the last child node by using the lastChild property, and removes it by using the removeChild() method. Once the last child node is removed, the second last node automatically becomes the last child node.
  2. Repeat the first step until there is no child node left.

The removed child node returned by the removeChild() method is no longer part of DOM. However, you can insert it back to the DOM if required.

What about innerHTML and textContent?

You could also use the innerHTML property to remove all child nodes:

// select target target 
const body = document.querySelector('body');

// remove all child nodes
body.innerHTML = '';

This approach is simple, but it may not be a suitable choice for high-performance applications because it invokes the browser's HTML parser to parse the new string and update the DOM.

If you don't want to invoke HTML parser, use the textContent property instead:

body.textContent = '';

According to MDN, the textContent property performs better than innerHTML as the browser doesn't have to invoke the HTML parser and can immediately replace all child nodes of the element with a single text node.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.