How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
<p id="foo"> <span>hello</span> <div>world</div> </p>
And I grab the node I want like so:
var myNode = document.getElementById("foo");
How could I remove the children of foo
so that just <p id="foo"></p>
is left?
Could I just do:
myNode.childNodes = new Array();
or should I be using some combination of removeElement
?
I’d like the answer to be straight up DOM; though extra points if you also provide an answer in jQuery along with the DOM-only answer.
Advertisement
Answer
In 2022+, use the replaceChildren()
API!
Replacing all children can now be done with the (cross-browser supported) replaceChildren
API:
container.replaceChildren(...arrayOfNewChildren);
This will do both:
- remove all existing children, and
- append all of the given new children, in one operation.
You can also use this same API to just remove existing children, without replacing them:
container.replaceChildren();
This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done without requiring innerHTML
, and in one step instead of multiple.