6

I have the following code

var style = document.createElement('style');
style.setAttribute("type", "text/css");
if (style.textContent) { // FF, Safari
    style.textContent = this.arg.css;
} else {
    style.innerHTML = this.arg.css;// FF, IE
}
document.getElementsByTagName('head')[0].appendChild(style);

This works fine in all browsers (also IE 9) but for IE7 and IE8, I get the following error

SCRIPT600: Unknown runtime error

The error points to the line

    style.innerHTML = this.arg.css;// FF, IE

What's wrong?

Omar Abid
  • 15,753
  • 28
  • 77
  • 108

1 Answers1

10

you can try this way

var style = document.createElement('style');
var text = this.arg.css;
style.setAttribute("type", "text/css");
if (style.styleSheet) {   // for IE
    style.styleSheet.cssText = text;
} else {                // others
    var textnode = document.createTextNode(text);
    style.appendChild(textnode);
}
var h = document.getElementsByTagName('head')[0];
h.appendChild(style);
Alex K
  • 6,737
  • 9
  • 41
  • 63
  • Thanks, it works. Just curious to know how "var textnode = document.createTextNode(text);" is useful? – Omar Abid Apr 11 '11 at 08:53
  • that is just a DOM way, it uses appendChild for any new elements (even text) – Alex K Apr 11 '11 at 08:56
  • I'm seeing some cases in IE8 where style.styleSheet is null, so the if fails and it falls through to the else, which then throws the Unknown Runtime Error. Any ideas why styleSheet would be null? – Herms Sep 13 '13 at 20:42
  • @Herms, if you see some cases for it - then you can maybe track and post the error when it happens? i haven't seen it – Alex K Sep 17 '13 at 11:13
  • 3
    Apparently IE has a limit on the number of stylesheets it allows, and if you've hit that limit this behavior will trigger. I'm fairly certain that's what I was running into. – Herms Sep 23 '13 at 18:22
  • @Herms, as a workaround in this case i may suggest to try using 1 stylesheet, and editing it (changing its `cssText`) each time you make changes – Alex K Sep 24 '13 at 12:53
  • @Herms, no I bet you're leaving out the line: style.setAttribute("type", "text/css"); which is required for IE8 –  Feb 05 '15 at 17:57