When working with the DOM in JavaScript, you may encounter scenarios where you need to remove child elements from a specific node. This guide will explore various approaches to addressing this task.
One simple method is to set the innerHTML property of the parent node to an empty string. While straightforward, this approach may not be suitable for high-performance applications as ittriggers the browser's HTML parser.
const myNode = document.getElementById("foo"); myNode.innerHTML = "";
<div>
A more granular approach is to remove each child node individually using the removeChild() method.
const myNode = document.getElementById("foo"); while (myNode.hasChildNodes()) { myNode.removeChild(myNode.lastChild); }
If you know the specific child elements you want to remove, you can combine removeChild() with querySelectorAll() to target and remove them more efficiently.
const myNode = document.getElementById("foo"); const childElements = myNode.querySelectorAll("span, div"); childElements.forEach((element) => { myNode.removeChild(element); });
The above is the detailed content of How to Efficiently Remove Child Elements from a Node in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!