What is the best way to empty a node in JavaScript

You can also just call node.replaceChildren() and it will empty the node. It's quick, clean, and makes your intention clear.


You have at least four options:

  1. Using innerHTML = "" as you've shown in the question. It will make sure the element on which you call it has no child nodes at all, and doesn't create any new nodes. It's specified and reliable cross-browser (although there's an IE bug that may or may not affect your code), and is probably fairly efficient.

  2. Using textContent = "", which is also specified and reliable cross-browser (IE9+) and, interestingly, IE11 (at least) doesn't seem to have the bug with textContent that it has with innerHTML. It also has the advantage of not requiring an HTML parser, where of course the string you give innerHTML is expected to be HTML. (Browsers may well have an optimization in place for when the string is blank, though.)

  3. You could use removeChild in a loop, but that involves potentially repeated function calls into the DOM:

    // assuming elm is the element
    while (elm.firstChild) {
       elm.removeChild(elm.firstChild);
    }
    
  4. You could replace the parent element with a clone omitting the children:

    // assuming elm is the element
    const clone = elm.cloneNode(false);
    parent.parentElement.replaceChild(clone, elm);
    elm = clone;
    

    Note that unlike the others, this will remove any event handlers on the parent element.

If I had to guess, I'd guess that textContent = "" would be fastest, at least if there are a lot of children. But performance usually doesn't matter, it's an extremely rare case where this will be the noticeably slow part of your code. If you run into a situation where it matters, test your actual code usihng each of the options in your target browsers and choose the one that works best.

People love synthetic benchmarks, but synthetic benchmarks are remarkably unreliable and sensitive to benchmark assumptions (such as the number of children being removed).

Tags:

Javascript