How to remove all children of the DOM element In JavaScript

Overview

We can remove all the children elements of the DOM element by setting the innerHTML of the element to an empty string.

The innerHTML property is used to set and get the HTML content within the element. Read more about innerHTML here.

Syntax

element.innerHTML=content

When we set the innerHTML of an element, all the child nodes of the element are replaced with the passed HTML contentThe passed HTML String is parsed internally.

Example

The code below demonstrates how to remove all the children of a DOM element:

Console
using innerHTML to remove all children

Explanation

In the code above,

  • Lines 5 to 9: We create a div element with 3 child elements.
  • Line 11: We access the div element by using getElementById method and store in the ele variable.

  • Line 12: We print the number of child elements present in the ele. In our case, 3 is printed.

  • Line 13: We set the empty string as an HTML content of the ele. This replaces the old HTML content.

  • Line 14: We print the number of child elements present in the ele. Now, 0 is printed.


In addition to the method above, we can also remove all elements of the DOM element in the following ways:

  1. Set textContent of the element to an empty string:
//html 
   <div id="parent">
     <p>Child 1</p>
     <p>Child 2</p>
     <p>Child 3</p>
   </div>
// js
let ele = document.getElementById('parent');
ele.childElementCount; // 3
// removed the child elements by setting textContent to empty string.
ele.textContent = "";
ele.childElementCount; // 0
  1. Remove all the last children of the element until the element becomes empty:
//html 
   <div id="parent">
     <p>Child 1</p>
     <p>Child 2</p>
     <p>Child 3</p>
   </div>
// js
let ele = document.getElementById('parent');
ele.childElementCount; // 3
// loop will continue until the "ele" has a child.
while(ele.lastChild) {
  ele.lastChild.remove();//removee the last child of "ele"
}
ele.childElementCount; // 0

Free Resources