Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a style tag in a web page from external javascript(js) file

Tags:

javascript

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);
    }
like image 965
Tokendra Kumar Sahu Avatar asked Dec 01 '11 13:12

Tokendra Kumar Sahu


2 Answers

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.

like image 28
Bergi Avatar answered Oct 22 '22 19:10

Bergi


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

like image 120
albert Avatar answered Oct 22 '22 19:10

albert