How to get a style attribute from a CSS class by javascript/jQuery?

I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.

There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.

If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it’s more exact).

I only tested on jsFiddle with some weak test cases, let me know if this works for you.

function getStyleRuleValue(style, selector, sheet) {
    var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
    for (var i = 0, l = sheets.length; i < l; i++) {
        var sheet = sheets[i];
        if( !sheet.cssRules ) { continue; }
        for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
            var rule = sheet.cssRules[j];
            if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
                return rule.style[style];
            }
        }
    }
    return null;
}

example usage:

var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.

var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]); 

edit:

I neglected to take into consideration grouped rules. I changed the selector check to this:

if (rule.selectorText.split(',').indexOf(selector) !== -1) {

now it will check if any of the selectors in a grouped rules matches.

Leave a Comment