Search code examples
javascriptinternet-explorerinternet-explorer-8prototypejs

Inserting <style> tags from a string in Internet Explorer


I'm loading a string via AJAX that reads like

<style>[some definitions]</style>
<h1>Lots of Markup</h1>
<p>follows here</p>

Using Webkit/Gecko everything works as expected — the markup is inserted, styles are applied. In IE (8) though the style-definitions are ignored. Actually, if you use the developer tools they are gone.

You can see in this JS-Fiddle that it doesn't work: http://jsfiddle.net/J4Yzr/

Also, I've seen that trick that you create a temporary DOM-Object, set it's innerHTML to your markup and extract your markup as DOM-Objects from your temporary element. That doesn't work with style tags (if I did it right, I'm using prototypeJS):

var text = '<style>h1{color:red;}</style> style added',
    el   = new Element('div').update(text);

console.log(el.firstChild);
//is a HTMLStyleElement in Webkit but a [object Text] in IE

Does anyone have a suggestion how to properly apply the <style> in IE if you get it from such a string?


Solution

  • Ok, it's crazy. Add a <br/>-Tag in front of your string and it works in Internet Explorer.

    <br/><style>[some definitions]</style><h1>Lots of Markup</h1>
    

    You don't even need to create that temporary DOM-Object to insert code into. Just append it in your site.

    What I'm doing now it insert the code with a <br/>-Tag and remove the <br/> afterwards. It's messy but it works.