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

I am developing a webpage in which I would like to add a dynamic style dynamically from an external javascript file .

I use 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); } 
+6
source share
2 answers

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

+1
source

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 the answers of the Alberts.

+1
source

Source: https://habr.com/ru/post/902841/


All Articles