# How to remove all children of an element using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 9, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-remove-all-children-of-an-element

> Learn how to remove all children of a DOM element by using the removeChild() method in 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:

```javascript
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](https://attacomsian.com/blog/javascript-dom-get-first-and-last-children-of-an-element) 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](https://attacomsian.com/blog/javascript-insert-element) it back to the DOM if required.

## What about `innerHTML` and `textContent`?

You could also use the [innerHTML](https://attacomsian.com/blog/javascript-update-element-html-markup) property to remove all child nodes:

```javascript
// 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](https://attacomsian.com/blog/javascript-update-element-text) property instead:

```javascript
body.textContent = '';
```

According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent), 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.
