Member-only story
How to Remove All Child Elements of a DOM Node in JavaScript?
Removing all child elements from a DOM node is something that we’ve to do sometimes in JavaScript.
In this article, we’ll look at how to remove all child elements of a DOM node with JavaScript.
Clearing innerHTML
One way to remove all child elements of an element is to set the innerHTML
property of the element to an empty string.
For example, if we have the following HTML:
<button>
clear
</button>
<div>
</div>
Then we can write the following JavaScript to add the elements to the div.
And we can clear the items when we click the clear button:
const div = document.querySelector('div')
const button = document.querySelector('button')for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = 'hello'
div.appendChild(p)
}button.addEventListener('click', () => {
div.innerHTML = ''
})
We get the div and the button with document.querySelector
.
Then in the for loop, we create the p
elements and add them to the div.
And then we call addEventListener
on the button
with 'click'
as the first argument…