patternjavascriptCritical
Remove all child elements of a DOM node in JavaScript
Viewed 0 times
domremovechildnodealljavascriptelements
Problem
How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
And I grab the node I want like so:
How could I remove the children of
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.
Say I have the following (ugly) HTML:
hello
world
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 ` 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.
Solution
In 2022+, use the
Replacing all children can now be done with the (cross-browser supported)
This will do both:
You can also use this same API to just remove existing children, without replacing them:
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
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.Context
Stack Overflow Q#3955229, score: 687
Revisions (0)
No revisions yet.