Home >Web Front-end >JS Tutorial >How to Remove All Child Nodes of a DOM Element in JavaScript?
How to remove all child elements of a DOM node (JavaScript)
In JavaScript, you can remove all child elements of a DOM node by A variety of ways to achieve this.
Option 1: Clear innerHTML
const myNode = document.getElementById("foo"); myNode.innerHTML = '';
This method is simple and easy, but may not be suitable for applications that require high performance because it will call the browser HTML parser (but the browser may optimize the case where the value is an empty string).
Option 2: Use removeChild
const myNode = document.getElementById("foo"); while (myNode.firstChild) { myNode.removeChild(myNode.firstChild); }
This method involves looping through the child elements and removing them one after another, and has better performance than option 1.
jQuery Options
If you are using jQuery, you can remove child elements using:
$("#foo").empty();
This will remove the child elements from the specified element Remove all child elements.
The above is the detailed content of How to Remove All Child Nodes of a DOM Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!