IE innerHTML CSS bug

Today I encountered a bug that affects every version of Internet Explorer from IE6 all the way through IE9. Here’s what happens.

The Bug

  1. Set a Javascript string variable containing CSS styles (<style> or <link>) followed by some HTML content, such as a <p> tag (in my application this happened via JSONP).
  2. Add a <div> node to the DOM
  3. Insert the content from #1 into the .innerHTML property of the <div>
  4. The content gets inserted, devoid of CSS styles.
<!-- these styles are ignored when inserted via innerHTML -->
  p { color: blue; }
<p>Hello, how are you!</p>

The Solution

The simple solution was to put the other markup before the <style> or <link> tag. Bizarre.

<p>Hello, how are you!</p>
<!-- these styles are applied when inserted via innerHTML -->
 p { color: blue; }

Because IE needs something that affects the layout before it will apply CSS styles in an innerHTML property, these will not work as style triggers:

  • <!-- a comment -->
  • <p></p> (or any other empty block-level HTML tag)

One thought on “IE innerHTML CSS bug”

  1. Unbelievable, but this actually worked out!
    Now the problem is to figure out what to print there.

    It was working when I did the same but with document.write(SAME CODE) thogh: I have it as document.write for inserting widget and innerHTML for preview, the problem was only in 2nd case.

    This page: still has this issue right now in IE7 but will be fixed at next site revision.

    Thanks for this solution.

Leave a Reply

Your email address will not be published. Required fields are marked *