Home >Web Front-end >JS Tutorial >How to Remove All Child Nodes of a DOM Element in JavaScript?

How to Remove All Child Nodes of a DOM Element in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 05:25:221014browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn