0

I'm trying to add some styles into a page using javascript

var style = document.createElement("style"),
style.innerHTML = ".firstChildTest div:first-child {width: 2px;}";

But ie6-8 are throwing an error when trying to use innerHTML on a style element. I also get the same error using

 style.append(document.createTextNode(".firstChildTest div:first-child {width: 2px;}"));

How do I inject styles into a style element in ie?

wheresrhys
  • 22,558
  • 19
  • 94
  • 162

2 Answers2

0

See the answer here: How do you copy an inline style element in IE?

function copy_style(style_text) {    
    var tmp_div = document.createElement('div');
    tmp_div.innerHTML = '<p>x</p><style type="text/css">' + style_text + '</style>';

    return tmp_div.getElementsByTagName('style')[0];
}

Note that you need the <p> tag in the innerHTML of the tmp_div. Without it, IE does not accept the style element.

Community
  • 1
  • 1
lambacck
  • 9,768
  • 3
  • 34
  • 46
0

IE before #9 cannot use childNodes to add text to a style (or script or option) element, And styles are supposed to be in the head of an html document.

function addStyle(str){
    var el= document.createElement('style');
    if(el.styleSheet) el.styleSheet.cssText= str;
    else{
        el.appendChild(document.createTextNode(str));
    }
    return document.getElementsByTagName('head')[0].appendChild(el);
}
kennebec
  • 102,654
  • 32
  • 106
  • 127