IE innerHTML bug

November 12th, 2008 tim Leave a comment Go to comments

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. }
  1. May 12th, 2009 at 01:11 | #1

    Your a javascript God. Thanks for the help. I’ve been bangning my head against the wall for hours.

  2. neo
    September 10th, 2009 at 15:09 | #2

    Great !
    Nice CODE !

  3. Mike
    October 9th, 2009 at 17:05 | #3

    Thanks for posting this, saved me from resorting to diesel fuel and a match ;p

    Great code :)

  4. fp
    April 22nd, 2010 at 15:27 | #4

    Not so good. It only works if it is not used for replace previous html code.

  1. No trackbacks yet.