4

I know that accessing and manipulating the DOM can be very costly, so I want to do this as efficiently as possible. My situation is that a certain div will always contain a list of items, however sometimes I want to refresh that list with a completely different set of items. In this case, I can build the new list and append it to that div, but I also need to clear out the out list. What's the best way? Set the innerHTML to the empty string? Iterate over the child nodes and call "removeChild"? Something else?

Bialecki
  • 30,061
  • 36
  • 87
  • 109
  • Does this answer your question? [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) – Inigo May 16 '23 at 21:59

4 Answers4

6

Have a look on QuirksMode. It may take some digging, but there are times for just this operation in various browsers. Although the tests were done more than a year ago, setting innerHTML to "" was the fastest in most browsers.

P.S. here is the page.

staticsan
  • 29,935
  • 4
  • 60
  • 73
0

set innerHTML to an empty string.

Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
0

Emphasis on the can be costly. It is not always costly; in fact when dealing with a small number of elements it can be trivial. Remember optimizations should always be done last, and only after you have demonstrable evidence that the specific aspect you want to improve is really your performance bottleneck.

I recommend avoiding mucking with innerHTML if possible; it's easy to mess up and do something nasty to the DOM that you can't recover from as gracefully.

This method is quite fast for 99.9% of cases, unless you are removing massive hierarchy chunks from the DOM:

while(ele.childNodes.length > 0) {
    ele.removeChild(ele.childNodes[ele.childNodes.length - 1])
}
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • i would think the easiest way to mess up and do something nasty to the DOM would be to write code that manipulates it. I fail to see how changing innerHTML is going to do anything nasty particularly if the DOM isn't of any interest to an application. – Scott Evernden Feb 06 '09 at 06:31
  • Why not just: while(elem.childNodes) elem.removeChild(firstChild); – James Feb 06 '09 at 08:51
0

I'd recommend testing a couple implementations on the browsers you care about. Different Javascript engines have different performance characteristics and different DOM manipulation methods have different performance on different engines. Beware of premature optimization and beware of differences in browsers.

Mr. Shiny and New 安宇
  • 13,822
  • 6
  • 44
  • 64