Bialecki
Bialecki

Reputation: 31071

What is the more efficient way to delete all of the children of an HTML element?

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?

Upvotes: 4

Views: 903

Answers (4)

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13898

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.

Upvotes: 0

staticsan
staticsan

Reputation: 30555

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.

Upvotes: 7

Rex M
Rex M

Reputation: 144162

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])
}

Upvotes: 0

Scott Evernden
Scott Evernden

Reputation: 39986

set innerHTML to an empty string.

Upvotes: 0

Related Questions