Is it possible to change the CSS stylesheet using JavaScript? (NOT the style of the object, but the stylesheet itself)

Is it possible to change the CSS stylesheet using JavaScript?

I am NOT talking about:

document.getElementById('id').style._____='.....'; 

I AM talks about the change:

 #id { param: value; } 

in addition, something dirty (to which we have not tried to use btw yet), for example, creating a new object in the head, innerHTML style tag, etc. Although this, even if it really worked, would create several problems since the style block is already defined elsewhere, and Im not sure when / if the browser will even parse the dynamically created style block?

+18
javascript html css stylesheet alter
Jul 08 '11 at 5:45 a.m.
source share
3 answers

As of 2011

Yes you can, but you will have compatibility issues between browsers:

http://www.quirksmode.org/dom/changess.html

Since 2016

Browser support has improved significantly (every browser is supported, including IE9 +).

  • The insertRule() method allows you to dynamically add rules to the stylesheet.

  • With deleteRule() you can delete existing rules from the stylesheet.

  • Rules in the stylesheet can be obtained using the cssRules attributes of the stylesheet.

+15
Jul 08 2018-11-11T00:
source share

We can use a combination of .insertRule and .cssRules to be able to do this before IE9 itself:

 function changeStylesheetRule(stylesheet, selector, property, value) { // Make the strings lowercase selector = selector.toLowerCase(); property = property.toLowerCase(); value = value.toLowerCase(); // Change it if it exists for(var i = 0; i < s.cssRules.length; i++) { var rule = s.cssRules[i]; if(rule.selectorText === selector) { rule.style[property] = value; return; } } // Add it if it does not stylesheet.insertRule(selector + " { " + property + ": " + value + "; }", 0); } // Used like so: changeStylesheetRule(s, "body", "color", "rebeccapurple"); 

Demo

+2
Jun 30 '16 at 20:58
source share

When I want to programmatically add a bunch of styles to an object, I find it easier to programmatically add a class to the object (such a class has styles associated with it in your CSS). You can control the priority order in your CSS so that the new styles of the new class can override the things you had before. This, as a rule, is much simpler than changing the stylesheet directly and works great in a cross browser.

+1
Jul 08 2018-11-11T00:
source share



All Articles