Home >Web Front-end >JS Tutorial >How to Remove All Child Elements from a DOM Node in JavaScript?

How to Remove All Child Elements from a DOM Node in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 06:12:14963browse

How to Remove All Child Elements from a DOM Node in JavaScript?

Remove All Child Elements of a DOM Node in JavaScript

The provided snippet of HTML code has a parent node ("foo") with two child elements ("span" and "div"). To remove all child elements from "foo," you can use the following methods:

DOM-Only Option 1: Clearing innerHTML

This approach involves clearing the innerHTML property of the parent node. However, this method may not be suitable for high-performance applications as it invokes the browser's HTML parser:

const myNode = document.getElementById("foo");
myNode.innerHTML = '';

jQuery Alternative

In jQuery, you can use the empty() method to remove all child elements from a node:

$('#foo').empty();

The above is the detailed content of How to Remove All Child Elements from a DOM Node 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