6

I am developing a web page in which I would like to add style tag dynamically from an external javascript file.

I am using this code that does not work

this.addStyle = function()
    {
        if (! this.inited) {
          alert("not inited");
          return;
         }
        var head = document.getElementsByTagName('head')[0],
        style = document.createElement('style'),
        rules = document.createTextNode('.bodys { bgcolor="red"; }');
        style.type = 'text/css';
        if(style.styleSheet)
            style.styleSheet.cssText = rules.nodeValue;
        else style.appendChild(rules);
            head.appendChild(style);
    }
1
  • Please use some code formatting for your question. Commented Dec 1, 2011 at 13:15

2 Answers 2

1

Change .bodys{ bgcolor="red"; } to .bodys{background-color:red}

Sign up to request clarification or add additional context in comments.

Comments

1

Not all browsers are applicable to generated text nodes. MediaWiki uses

var s = document.createElement( 'style' );
s.type = 'text/css';
s.rel = 'stylesheet';
if ( s.styleSheet ) {
    s.styleSheet.cssText = text; // IE
} else {
    s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
}

Of course also follow alberts answer.

1 Comment

I'm not sure whether really s.rel = 'stylesheet'; is needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.