Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible to alter a CSS stylesheet using JavaScript?

I am NOT talking about:

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

I AM talking about altering:

#id {     param: value; } 

besides doing something dirty (which we haven’t tried yet btw), like creating a new object in the head, innerHTML a style tag in there, etc. Although this, even if it did work, would pose a few issues as the style block is already defined elsewhere, and I’m not sure when/if the browser would even parse a dynamically created style block?

like image 438
anonymous-one Avatar asked Jul 08 '11 05:07

anonymous-one


People also ask

Can you edit a CSS file with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can JavaScript change HTML styles CSS?

The HTML DOM allows JavaScript to change the style of HTML elements.

How can the style of an element be changed in JavaScript?

Select the element whose style properties needs to be change. Use element. style property to set the style attribute of an element. Set the properties either by using bracket notation or dash notation.


2 Answers

As of 2011

Yes you can, but you will be facing cross-browser compatibility issues:

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

As of 2016

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

  • The insertRule() method allows dynamic addition of rules to a stylesheet.

  • With deleteRule(), you can remove existing rules from a stylesheet.

  • Rules within a stylesheet can be accessed via the cssRules attributes of a stylesheet.

like image 67
Mathieu Rodic Avatar answered Sep 19 '22 20:09

Mathieu Rodic


We can use a combination of .insertRule and .cssRules to be able to do this all the way back to IE9:

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 < stylesheet.cssRules.length; i++) {         var rule = stylesheet.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

like image 35
Zach Saucier Avatar answered Sep 19 '22 20:09

Zach Saucier