How to remove all children from a DOM element

By

Learn how to remove all the children of a DOM element, the fastest way by setting innerHTML to an empty string, or with a while loop calling removeChild().

~~~

To remove all the children of a DOM element you can set its innerHTML property to an empty string, or you can loop over its children and remove them one by one with removeChild().

Say you have a list of notifications, and you want to clear them all when the user clicks a “clear” button.

First, get a reference to the element. Use querySelector() to identify it:

const list = document.querySelector('#notifications')

The fastest way: set innerHTML to an empty string

The quickest solution looks like this:

list.innerHTML = ''

The browser drops every child node at once. In most performance benchmarks I checked, this is the fastest option.

There’s a similar trick with textContent:

list.textContent = ''

It does the same job, and it skips the HTML parser entirely, so it can be even faster on some browsers.

Removing children one by one

Another solution is a loop. Check if the firstChild property is defined (the element has at least a child) and remove it:

const list = document.querySelector('#notifications')
while (list.firstChild) {
  list.removeChild(list.firstChild)
}

The loop ends when all children are removed.

Why would you pick this over innerHTML? Because removeChild() returns the node you removed. If you need to do something with each child before it goes away, like saving its text somewhere, this approach gives you a hook to do it.

What about replaceChildren()?

Modern browsers also give us replaceChildren(). Called with no arguments, it clears everything:

list.replaceChildren()

It’s readable and it works in every current browser. If you don’t need to support old browsers, this is the cleanest option.

Watch out for stored references

One thing to be careful with: removing children does not clear variables that point to them.

const first = list.firstChild
list.innerHTML = ''
console.log(first) //still the node, now detached

The node still exists in memory because your variable references it. It’s just no longer in the page. If you keep collections of child nodes around after clearing the parent, you’re holding onto detached DOM nodes, and that memory won’t be freed. Set those variables to null when you’re done with them.

~~~

Related posts about platform: