InnerHTML in IE with the Pre Tag


Tonight I had the lovely experience of finding yet another IE quirk. And yay - it affects IE7. I discovered that when using the innerHTML property to update an element the text is normalized. When that element is a <pre> tag, normalization is exactly what you do not want to happen - you want your text to be defined as you defined it, not in some other quirky way that the browser engine decided to rewrite it as. The whole point of the <pre> tag is preformatted text.

I did find a workaround for this problem, and I'll share that with you tonight :)

The workaround involves the use of the outerHTML element rather than innerHTML. Apparently, outerHTML is not normalized. Go figure.

collapsehide line numbers
Sample Code
 1<br />
 2if (elem.tagName == "PRE" && "outerHTML" in elem){<br />
 3  elem.outerHTML = '<pre>' + yourtext + '</pre>';<br />
 4	//alert('hey, this might work...');<br />
 5} else {<br />
 6 elem.innerHTML = yourtext;<br />
 7} <br />
Code ©SteveKallestad.com

I ran into this problem making some updates to my syntax highlighter (still not released, but getting closer). outerHTML is an IE specific property - part of Microsoft's "embrace and extend" strategy - which in my opinion has turned out as more of a "break and then find workarounds" strategy. How much better would IE be if they followed W3 standards? It probably would be about as good as firefox. :)



Join The InnerHTML in IE with the Pre Tag Discussion