Last Updated: December 22, 2020
·
51.92K
· 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.

5 Responses
Add your response

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 ·

Can you share why removeChild is faster than emptying innerHTML?

over 1 year ago ·

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 ·

@Havunen, I followed your link and emptying firstChild was clearly faster than innerHTML = '';. I don't know what browser version you're running.. I'm on Chrome 70 and the difference is obvious. 83% faster (the winning method only looks up .firstChild once per loop instead of twice, which yields a small perf increase).

over 1 year ago ·

Why don't use this ?
el.querySelectorAll("*").forEach(el => el.remove())

over 1 year ago ·