Categories
JavaScript Answers

How to remove all the children DOM elements in div with JavaScript?

Spread the love

Sometimes, we want to remove all the children DOM elements in div with JavaScript.

In this article, we’ll look at how to remove all the children DOM elements in div with JavaScript.

How to remove all the children DOM elements in div with JavaScript?

To remove all the children DOM elements in div with JavaScript, we can use the removeChild method.

For instance, we write

while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}

to use a while loop to check if the node has any child nodes left with hasChildNodes.

Then we call remove.removeChild to remove the node‘s lastChild in the loop body.

Conclusion

To remove all the children DOM elements in div with JavaScript, we can use the removeChild method.

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 *