How to remove all children from DOM element

Given a DOM element, how to delete all its child elements?

Given an item in the DOM, usequerySelector()Identify it, like this:

const item = document.querySelector('#itemId')

Then, to delete all its child elements, you have several different solutions.

The fastest method is as follows:

item.innerHTML = ''

Another solution suggested is: create a loop to check if it existsfirstChildDefine the attribute (the element has at least one child), and then delete it:

const item = document.querySelector('#itemId')
while (item.firstChild) {
  item.removeChild(item.firstChild)
}

After deleting all the children, the loop ends.

In most of the performance benchmarks I checked, the first seemed to be the fastest solution.

Download mine for freeJavaScript beginner's manual


More browser tutorials: