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.
element.innerHTML=content
When we set the innerHTML
of an element, all the child nodes of the element are replaced with the
The code below demonstrates how to remove all the children of a DOM element:
In the code above,
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:
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
//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