How to empty a DOM element using JavaScript


Borislav Hadzhiev

Wed Jan 05 20222 min read


Photo by Fineas Anton

Empty a DOM element using JavaScript #

Use the replaceChildren() method to empty an element, e.g. element.replaceChildren(). When the replaceChildren method is invoked without passing it any arguments, the method empties the element of all its children.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <p>One</p> <p>Two</p> <p>Three</p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const box = document.getElementById('box'); box.replaceChildren();

We called the replaceChildren method without passing it any parameters, which emptied the element of all its children.

The method can also be used to replace the existing children of an element with a provided set of children.
const box = document.getElementById('box'); const p1 = document.createElement('p'); p1.innerHTML = `<span style="background-color: lime">Apple</span>`; const p2 = document.createElement('p'); p2.innerHTML = `<span style="background-color: orange">Orange</span>`; box.replaceChildren(p1, p2); // ✅ If you have a collection of elements // use spread operator (...) to unpack the collection // box.replaceChildren(...[p1, p2]);

By using the replaceChildren method, we are able to empty the element and add a new set of children to it in a single step, which is a bit faster.

The method takes one or more Node object or strings, with which it replaces the element's existing children.

Empty a DOM element using textContent #

To empty a DOM element, set the element's textContent property to an empty string, e.g. element.textContent = ''. Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.

const box = document.getElementById('box'); box.textContent = '';

The textContent property can be used to read and set the text content of an element.

When using the property to set a node's text content, all of the element's children are removed and replaced with the provided string value.

In the example above, we effectively replace all of the element's children with an empty string.

You might also see the innerHTML property being used in a similar way.

const box = document.getElementById('box'); box.innerHTML = '';

This achieves the same result, however it might be slower because setting the innerHTML property uses the browser's HTML parser.

The textContent property doesn't use the browser's HTML parser and might be faster if the element has many children.

Which approach you pick is a matter of personal preference. I'd go with the replaceChildren method as it is direct, easy to read and can be used to replace the removed child elements in a single step.
Use the search field on my Home Page to filter through my more than 1,000 articles.