Cute solutions and something else...

innerHTML vs createElement

Published Tuesday, July 04, 2006 by Роман Рахман.

AFAIK creating DOM elements with the help of Javascript is a very popular task. And there exist two popular common methods to do it: to use parentNode.innerHTML property or methods document.createElement() + parentNode.appendChild(node). Surely there are other methods like table.insertRow() or select.options[index] = new Option() but these ones are commonly used. Let's analyze them according to the following characteristics: compliance, speed, memory usage. See the sample page here. It demonstrates how to insert 1000 equal images about 1Kb size in the DIV via innerHTML or createElement.

1. Compliance


As there is no public specification for this property, implementations differ widely. For example, when text is entered into a text input, IE changes the value attribute of the input's innerHTML property but Gecko browsers do not.

It should never be used to write parts of a table—W3C DOM methods are to be used for that—though it can be used to write an entire table or the content of a cell.

createElement: +1

2. Speed

  • innerHTML — 1524, 1472, 1483
  • createElement — 4687, 2584, 2573 (strange speed-up after page refresh)
Internet Explorer 6.0 (woah! really rocket-like speed)
  • innerHTML — 360, 320, 211
  • createElement — 360, 421, 390
Usually innerHTML is much more quicker than createElement in Firefox and a bit quicker in Inernet Explorer

innerHTML: +1

3. Memory usage

See these two memory diagrams below (private bites of Internet Explorer process):

use innerHTMLuse createElement

So... Internet Explorer uses more memory when you try to insert HTML with images via innerHTML instead of createElement. Don't forget it!
Firefox doesn't have similar memory problems.

createElement: +1

The final score - 2:1 in favor of createElement

In most cases createElement is a more powerful method. And using something like
domEl() is more useful and quite simple.

2 Responses to “innerHTML vs createElement”

  1. Anonymous Dao 

    Point 1 (Compliance) isn't really an advantage of createElement. The first paragraph is mainly valid vor reading innerHTML, not for setting it, hence it's not related to createElement. The second paragraph is a limitation for tables, but it doesn't devalue innerHTML in general.

    Then I think the speed advantage exceeds the tiny memory difference.

    So this scoring seems vacuous, kind of. One should know the differences and then decide what is more appropriate for a certain case.

  2. Anonymous Roman Rahman 

    About speed vs memory - I've used innerHTML in ajax-base chat (inserting html with images like layout decoration, smiles etc.) And after a few hours my IE has catched a heap of memory. So, speed isn't so important some time :)

Leave a Reply

About me

  • I'm Роман Рахман
  • From Донецк, Ukraine
  • My profile