Cute solutions and something else...

innerHTML vs createElement 2

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

DOM:element.innerHTML

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

Firfox 1.5.0.4
  • 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.

About me

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

Links