Categories
JavaScript Answers

How to Remove All the Child DOM Elements in a Div with JavaScript?

Spread the love

We can remove all child nodes from an element with a few node properties.

For instance, if we have the following HTML:

<div>  
  <p>  
    foo  
  </p>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can remove all the p elements by writing:

const node = document.querySelector('div')  
while (node.hasChildNodes()) {  
  node.removeChild(node.lastChild);  
}

We get the div with document.querySelector .

Then we use a while loop to check if there’re any child nodes left with node.hasChildNodes .

And if there are any left, we call node.removeChild with node.lastChild to remove the last child node.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *