Internet Explorer and the innerHTML Property

Recently while helping a friend deal with the joys of cross-browser JavaScript when working with widgets, I was reminded of a painful quirk in how Intenert Explorer handles the innerHTML property of DOM elements in some cases.  In particular, DOM elements that are part of a table, or are a child to a table (no matter how many levels deep), can’t have the innerHTML property set at run time.  Doing so produces a completely unhelpful error message and crashes the rendering engine.  This is not only true for tables, but unfortunately happens with several other HTML elements in regard to Internet Explorer.

So, how does one get around this unfortunate problem?  Well, the best method I’ve found is to set the innerHTML property when the element is not yet attached to the DOM or is attached in a “safe” place (usually at the BODY tag).  To make this process simpler, I generalized this into a function that creates a new DOM node of the same type, preserves any attributes I care about, sets the innerHTML property, and replaces the original node in the DOM with this new node having the desired innerHTML.  Here’s the function for reference:

function replace_html(el, html) {
	if( el ) {
                var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
                var newEl = document.createElement(oldEl.nodeName);

                // Preserve any properties we care about (id and class in this example)
                newEl.id = oldEl.id;
                newEl.className = oldEl.className;

                //set the new HTML and insert back into the DOM
                newEl.innerHTML = html;
                if(oldEl.parentNode)
        	        oldEl.parentNode.replaceChild(newEl, oldEl);
                else
		        oldEl.innerHTML = html;

                //return a reference to the new element in case we need it
                return newEl;
	}
};

Hopefully this function will help someone out there work around this problem a little faster than I originally did.

This entry was posted in Code, Javascript and tagged , , , . Bookmark the permalink.

34 Responses to Internet Explorer and the innerHTML Property