Manipulating CSS with JavaScript

I would like to use JavaScript to control my CSS. At first it was thought that it was a nice little script to try different colors for my accordion menu along with different backgrounds / title / content - / ... background-colors from the input field.

I understand how to get input value using js.

I understand how CSS is controlled by 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 > a.active {
/* css */
}

How to change the properties of such styles using JavaScript?

+2
source share
3 answers

CSS JavaScript. stylesheet, - :

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 , { .

, , , . , , .

.

jsFiddle.

+3

I followed Teemu's answer with underscore. http://jsfiddle.net/6pj3g/4/

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

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

All Articles