2 Ways to Remove All Children Elements in JavaScript

There are situations when you have to remove all the children elements in javascript. Different approaches can be used to remove all the children with javascript but in this article, you can learn the 2 best ways to get the job done.

Using While Loop to Remove Children Elements

You can use a while loop on the parent node to delete all the child elements. The loop will run until the firshChild is removed from the DOM. Here is a simple example of removing all the children with a while loop.

In the above example, when the button is clicked, all the child elements from the div are removed. You can check the working example on codepen.

Method 2: Using forEach Loop to Remove All Child Elements

This method is even more simple than the first. In this method, the HTML collection of children elements will be converted to an array and then all the elements will be removed from the DOM. Check the example below that do the same thing in a better way.

The above example iterates each child element and calls the remove method to remove the current element from the DOM.


You can remove all the child elements with JavaScript on a web page. There are many ways to do this but using a while loop or a forEach loop with .remove() is a better solution. You can read more about the remove function on mozilla documentation.

Latest articles

Related articles