nygghw
Last Updated: September 29, 2017
·
19.54K
· thomaslindstr_m

Don't use innerHTML to empty DOM elements

Avoiding the use of innerHTML when emptying DOM elements (or anything else) can increase performance greatly.

Take a look for yourself: http://jsperf.com/innerhtml-vs-removechild/37

In Chrome 26, using a while-loop to remove children was an incredible 400 times faster! This is a desktop browser we're talking about!

Instead of doing this

el.innerHTML = '';

to empty your DOM elements, you should instead use this

while (el.firstChild) el.removeChild(el.firstChild);

which is, like I said, about 400 times faster than innerHTML on a modern desktop browser.

Even the use of innerText to clean the DOM element (known to be faster than innerHTML) doesn't compare, and is a little more than 10 times slower than the while-loop.

3 Responses
Add your response

19289

It really surprised me the difference in times, but be careful since IE8 ignores empty text nodes when you use firstChild or childNodes for example.

over 1 year ago ·
28565

Can you share why removeChild is faster than emptying innerHTML?

over 1 year ago ·
28648

This is bullsht, always when somebody tells you this is 1000x faster than other one, doubt it. In his jsperf he is comparing (remove + setting) vs remove once and do nothing. This is so stupid it hurts.... here is better comparison: https://jsperf.com/innerhtml-vs-removechild/418 and suprisingly (not) what he recommended is slower... also everybody should learn to use irHydra to compare JS, jsperf can be really tricky beacause modern JS engines optimize the code away and you are comparing basically nothing.

over 1 year ago ·