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);
}
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.
Change .bodys{ bgcolor="red"; }
to .bodys{background-color:red}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With