0

To empty a divs contents, consider for example a graph_container div containing svg element which in turn contains thousands of elements, we can do

graph_container.innerHTML = ''

or a more efficient way to remove elements is

while (graph_container.firstChild)
    graph_container.removeChild(graph_container.firstChild);

Benchmarks can be found at https://jsperf.com/innerhtml-vs-removechild

But it's hard to perceive why chucking all sub-elements without even looking at them is not fast or why removing all subelements elementwise is better for DOM.

Why can't the DOM remove links to the subtree and destroy the subtree altogether, which I think should be efficient than the while loop which can neither be parallized nor be executed in one shot?

EDIT: The question mentioned in the comments, is about how to remove them and the answer has both the methods stated in the question. But it does not tell why one is better than the other and does not answer the question above.

Saravanabalagi Ramachandran
  • 8,551
  • 11
  • 53
  • 102
  • Possible duplicate of [Remove all child elements of a DOM node in JavaScript](https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript) – MatthewG Sep 15 '18 at 14:26
  • @MatthewG The answers from that question are part of this question; I don't see how this can be a duplicate... It's not necessarily a good question (asking random people on the internet why a browser does something is asking for supposition), but I don't think it's a duplicate of that question. – Heretic Monkey Sep 15 '18 at 17:51
  • and what is the question? – Bekim Bacaj Sep 16 '18 at 18:45

0 Answers0