Changing a CSS rule-set from Javascript

You can, but it's rather cumbersome. The best reference on how to do it is the following article: Totally Pwn CSS with Javascript (web archive link).

I managed to get it to work with Firefox and IE - I couldn't in Chrome, though it appears that it supports the DOM methods.ricosrealm reports that it works in Chrome, too.


This is a modern version based on Totally Pwn CSS with Javascript. It's ES6 I hope don't mind.

function getCSSRule(ruleName) {
    ruleName = ruleName.toLowerCase();
    var result = null;
    var find = Array.prototype.find;

    find.call(document.styleSheets, styleSheet => {
        result = find.call(styleSheet.cssRules, cssRule => {
            return cssRule instanceof CSSStyleRule 
                && cssRule.selectorText.toLowerCase() == ruleName;
        });
        return result != null;
    });
    return result;
}

This function returns a CSSStyleRule that you can use like this:

var header = getCSSRule('#header');
header.style.backgroundColor = 'red';

Also document.styleSheets list references of the CSSStylesSheets Objects. Other way to acces a specific sytleSheet in the page is by assigning an id to the style or link element in the html code, and get it in javascript using document.getElementById('my-style').sheet. This are some useful methods:

Major Browsers and IE9+ : insertRule(), deleteRule(), removeProperty().

Major Browsers, Firefox? and IE9+ : setProperty().

<stye id="my-style" ...
....
var myStyle = document.getElementById('my-style').sheet
myStyle.insertRule('#header { background: red; }', 0);

It is also possible to dynamically create a new style element to store dynamic created styles, I think should be way to avoid conflicts.

Tags:

Javascript

Css