Remove all Children of an DOM Node in JavaScript

June 26, 2020

Using innerHTML

To remove an all children of a DOM Node , you can set innerHTML as an empty string,

Consider the Node as

<div id="parent">  
    <p>hi</p>
    <span>hello</span>
    <div>Everyone</div>
</div>

To remove the elements of parent

document.getElementById("parent").innerHTML = "";

This will remove all the child elements.

Setting innerHTML doesn’t remove the event handlers of the child nodes, resulting in a memory leak.

Using textContent

You can set textContent as an empty string, to remove the elements of parent

document.getElementById("parent").textContent = "";

This will remove all the child elements.

Setting innerText as empty string also removes the child elements


Removing the Last Element until the parent is empty

To remove all child of DOM Node:

  • Check if the parent has childElements using firstChild

    • If the parent has child element then remove the last element
    • repeat the first steps until there is no remaining child Element
    function removeAllChild(id) {
        const myNode = document.getElementById(id);
        while (myNode.firstChild) {
            myNode.removeChild(myNode.lastChild);
        }
    }

You checked if a node has firstChild but removed the lastChild because it is faster to read the first element and faster to delete the last element.


Adding removeAllChild method to Element prototype

You can add a removeAllChild method to Element prototype using defineProperty.

if( typeof Element.prototype.clearChildren === "undefined" ) {
    Object.defineProperty(Element.prototype, "removeAllChild", {
      configurable: true,
      enumerable: false,
      value: function() {
        while(this.firstChild){
            this.removeChild(this.lastChild);
        }
      }
    });
}

Replacing parent node by cloning

You can clone the parent node without child elements, then we can replace the parent element with the cloned element clone the element to be emptied Replace the element using parentNode.replaceChild(newNodeToReplace, oldNodeToBeReplaced)

var parent = document.getElementById("parent")
var clone = parent.cloneNode(false);
var grandParent = parent.parentNode;
grandParent.replaceChild(clone, parent);

If you're using jQuery , then you can simply call

$("#parent").empty();

To compare the performance you can check here


Please donate here, for making more tutorials.