IE innerHTML bug

Explorer throws an unknown error when you set innerHTML

The bug seems to only occur for certain markup. I’m not 100% sure what the defining problem is, except that markup containing block elements like <div> and <p> seem to invoke the error. Anyway, this drove me up the wall recently so I thought I’d share the work around I came up with.

In short, the technique is to use a temporary element to set innerHTML first. IE doesn’t complain about this, possibly because the element is not a part of the tree. Then append the child nodes of the temporary element to the target element and all is good with the world.

  1. /**
  2.  * IE-safe innerHTML setter
  3.  */ 
  4. function setElementHTMLById( id, html ){ 
  5.    try { 
  6.       var El = document.getElementById(id); 
  7.       if( El.attachEvent ){ 
  8.          var elTmp = document.createElement(‘div’); 
  9.          elTmp.innerHTML = html; 
  10.          El.innerHTML = ; 
  11.          for( var i = 0; i < elTmp.childNodes.length; i++ ){ 
  12.             El.appendChild( elTmp.childNodes[i] ); 
  13.          } 
  14.       } 
  15.       else { 
  16.          El.innerHTML = html; 
  17.       } 
  18.    } 
  19.    catch( Er ){ 
  20.       return false; 
  21.    } 
  22.    return El.innerHTML; 
  23. }