This post isn't about the pros and cons of innerHTML vs. W3C DOM methods. That has been hashed and rehashed elsewhere. Instead, I'll show how you can combine the use of innerHTML and DOM methods to make your code potentially hundreds of times faster than innerHTML on its own, when working with large numbers of elements.

In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs. creating new ones. Knowing this, we can combine the speed of destroying elements by removing their parent using the standard DOM methods with creating new elements using innerHTML . (This technique is something I discovered during the development of RegexPal, and is one of its two main performance optimizations. The other is one-shot markup generation for match highlighting, which avoids needing to loop over matches or reference them individually.)

The code:

function replaceHtml(el, html) { var oldEl = typeof el === "string" ? document.getElementById(el) : el; /*@cc_on oldEl.innerHTML = html; return oldEl; @*/ var newEl = oldEl.cloneNode(false); newEl.innerHTML = html; oldEl.parentNode.replaceChild(newEl, oldEl); return newEl; };

You can use the above as el = replaceHtml(el, newHtml) instead of el.innerHTML = newHtml .

innerHTML is already pretty fast...is this really warranted?

That depends on how many elements you're overwriting. In RegexPal, every keydown event potentially triggers the destruction and creation of thousands of elements (in order to make the syntax and match highlighting work). In such cases, the above approach has enormous positive impact. Even something as simple as el.innerHTML += str or el.innerHTML = "" could be a performance disaster if the element you're updating happens to have a few thousand children.

I've created a page which allows you to easily test the performance difference of innerHTML and my replaceHtml function with various numbers of elements. Make sure to try it out in a few browsers for comparison. Following are a couple examples of typical results from Firefox 2.0.0.6 on my system:

innerHTML (destroy only): 156ms innerHTML (create only): 15ms innerHTML (destroy & create): 172ms replaceHtml (destroy only): 0ms ( ) replaceHtml (create only): 15ms (~ same speed) replaceHtml (destroy & create): 15ms ( ) innerHTML (destroy only): 14703ms innerHTML (create only): 250ms innerHTML (destroy & create): 14922ms replaceHtml (destroy only): 31ms ( ) replaceHtml (create only): 250ms (~ same speed) replaceHtml (destroy & create): 297ms ( )