Manipulating CSS with JavaScript

Solution 1:

There's no way to manipulate some CSS styles directly with JavaScript. Instead you can change a rule in a stylesheet itself, something like this:

var changeRule = function(selector, property, value) {
        var styles = document.styleSheets,
            n, sheet, rules, m, done = false;
        selector = selector.toLowerCase();
        for(n = 0; n < styles.length; n++) {
            sheet = styles[n];      
            rules = sheet.cssRules || sheet.rules;
            for(m = 0; m < rules.length; m++) {
                if (rules[m].selectorText.toLowerCase() === selector) {
                    done = true;
                    rules[m].style[property] = value;
                    break;
                }
            }
            if (done) {
                break;
            }
        }
    };
changeRule('div:hover', 'background', '#0f0');

selector must match exactly an exisiting selector, only spaces between selector text and { are ignored.

You can develope the code to find and change partial hits of selector names, or just check a particular stylesheet instead of all of them. As it is, it's also quite expensive when having tens of stylesheets with thousands of rules.

Unfortenately pseudo elements can't be manipulated with this snippet.

A live demo at jsFiddle.

Solution 2:

All DOM elements have a style object that can be altered by JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style?redirectlocale=en-US&redirectslug=Web%2FAPI%2Felement.style

Or if you're using jQuery:

http://api.jquery.com/css/

You can target elements and manipulate their propertoes, but you do not alter the rules.

A common approach if you want to alter large numbers of style properties is to alter elements' class names to change their appearance. This can be done with the className property, or if you're using jQuery: addClass and removeClass.