How to clear all children within a parent element using JavaScript
Last updated: July 25, 2022.
A simple way to clear the inner-contents of an element is to set the innerHTML
property of the parent to an empty string. This overwrites any existing content with this new value:
<div id="parent">
<span>Content</span>
<img src="myImage.png" alt="My image">
<p>Text</p>
Thanks for reading!
</div>
<script type="text/javascript">
parent = document.getElementById('parent');
console.log(parent.children.length); // 3
parent.innerHTML = "";
console.log(parent.children.length); // 0 (div has not inner content)
</script>
Alternatively, for the same result, you can loop through the children of the parent element, removing one each time until there are no more children:
<div id="parent">
<span>Content</span>
<img src="myImage.png" alt="My image">
<p>Text</p>
Thanks for reading!
</div>
<script type="text/javascript">
parent = document.getElementById('parent');
console.log(parent.children.length); // 3
while(parent.firstChild){ // while there is still a child inside the parent
parent.removeChild(parent.firstChild); // remove the first child
}
console.log(parent.children.length); // 0
</script>
In the tests we conducted using JSBEN.CH, the innerHTML
solution was found to be about 10% faster than looping, though the difference was small enough that it could vary by browser.