How can I remove all children in JavaScript from a DOM node?
If I grab the node with:
var myNode = document.getElementById("foo");
how can I remove all child elements so that only
is left?
Would myNode.childNodes = new Array(); work, or should I use removeChild? A straightforward DOM solution is preferred, but an additional jQuery example would also be helpful.
I’ve tackled this one before, and here’s a common DOM-only solution to remove all children JavaScript users find reliable:
Using a while
loop with removeChild()
:
var myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
This method will repeatedly remove the first child of myNode
until no children remain. Since firstChild
will be null
once all children are removed, the loop stops on its own, making this a straightforward and efficient solution without needing any libraries.
Another way to remove all children in JavaScript is by setting the innerHTML
to an empty string, which achieves the same result in a single line:
var myNode = document.getElementById("foo");
myNode.innerHTML = "";
This DOM-only approach clears out all child nodes quickly and is highly efficient for most use cases. It’s worth noting that using innerHTML = ""
not only removes child nodes but also clears any associated event listeners attached to those child elements.
If you’re already using jQuery, you can leverage its .empty()
method to remove all children in JavaScript from the #foo
element in a single, clean call:
$("#foo").empty();
The .empty()
method clears out all child elements of #foo
, and like innerHTML = ""
, it will also remove any associated events on those children. It’s concise and integrates well if you’re already working within a jQuery-based project.