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
Release: 2024-12-08 06:12:14
Original
962 people have browsed it

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 = '';
Copy after login

jQuery Alternative

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

$('#foo').empty();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template