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.
- /**
- * IE-safe innerHTML setter
- */
- function setElementHTMLById( id, html ){
- try {
- var El = document.getElementById(id);
- if( El.attachEvent ){
- var elTmp = document.createElement(‘div’);
- elTmp.innerHTML = html;
- El.innerHTML = ”;
- for( var i = 0; i < elTmp.childNodes.length; i++ ){
- El.appendChild( elTmp.childNodes[i] );
- }
- }
- else {
- El.innerHTML = html;
- }
- }
- catch( Er ){
- return false;
- }
- return El.innerHTML;
- }