Manipulating CSS with JavaScript

I would like to use JavaScript to manipulate my CSS. First it was just thought to be a nice little script to try out different colors for my accordion menu together with different backgrounds/title-/content-/... background-colors from an input field.

I understand how I get the input value with js.

I understand how CSS is manipulated by using getElementById(), getElementsByClassName(), getElementsByTag(), and getElementsByName().

Now, the problem is that my CSS looks like this:

.accordion li > a {
  /* some css here */
.sub-menu li a {
/* some css here */
.some-class hover:a {
/* css */
.some-other-class > li > {
/* css */

How would I change the properties of such stylings with JavaScript?



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;
            if (done) {
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.


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

Or if you're using jQuery:

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.


I've implemented Teemu's answer with underscore.

var rule = _.chain(document.styleSheets)
    .map(function(sheet){return _.flatten(sheet.cssRules)})
    .find(function(rule){ return rule && rule.selectorText && (rule.selectorText.toLowerCase() === selector.toLowerCase())})

if (rule){[property] = value;
} else {
    throw 'selector not found: ' + selector;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.