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
Example
The code below demonstrates how to remove all the children of a DOM element:
Explanation
In the code above,
- Lines 5 to 9: We create a
divelement with3child elements.
-
Line 11: We access the
divelement by usinggetElementByIdmethod and store in theelevariable. -
Line 12: We print the number of child elements present in the
ele. In our case,3is 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,0is printed.
In addition to the method above, we can also remove all elements of the DOM element in the following ways:
- Set
textContentof 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
- 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