innerHTML - Should I use it or not?

There is much controversy over the use of innerHTML in the channel. There are those who know what they're doing that swear by it and those that know what they're doing who swear at it. There are also a lot of people who don't know what they're doing that use it blindly

For some time now, the JSBot and his predecessor RTFS have included a factoid warning against it's use. This first appeared in order to warn those who weren't so aware so that they wouldn't blindly go ahead. This has led to some fierce arguments amongst the more advanced users.

To take the heat out of the argument, this article is all about the pitfalls of innerHTML and how to avoid them. It's not a flame fest from either side.

The factoid now reads:

InnerHTML is fast, but has its quirks. DOM methods are a good alternative - without the speed and readability (http://xrl.us/bmaiz). To read a list of innerHTML quirks and possible workarounds, see http://fn-js.info/faq/innerHTML)

Index

Coming Soon

  • Pouring content from XMLHttpRequest's textContent
  • Deleting content from a page

Adding a row to a table in IE

In Firefox and other browsers, you can use innerHTML to add a row to a table:

yourTBody.innerHTML += "<tr><td>Whatever goes here</td></tr>";
But this wont work in IE. There's a couple of options:

Use DOM methods:

var tr = document.createElement('tr');
var td = document.createElement('td');
td.appendChild( document.createTextNode("Whatever goes here") );
tr.appendChild( td );
yourTBody.appendChild( tr );

Or use this method of using innerHTML + DOM:

var div = document.createElement('div'); 
div.innerHTML = '<table><tr><td>Whatever goes here</td></tr></table>';
yourTBody.appendChild(div.firstChild.rows[0]);
It uses innerHTML to create an entire table rather than just the single TR, and then uses DOM methods to pull the TR out of that table and put it into the tbody that you want it in.

Turning HTML into DOM

Woosta has a handy tool that turns most (well formed) HTML into working DOM code: http://rick.measham.id.au/paste/html2dom.htm

Woosta gave up on anybody doing anything constructive with this page and made the decision to remove all argument and just talk about the problems. Table row code by Woosta except for innerHTML+DOM code by makk