Find all CSS rules that apply to an element

Since this question currently doesn’t have a lightweight (non-library), cross-browser compatible answer, I’ll try to provide one:

function css(el) {
    var sheets = document.styleSheets, ret = [];
    el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector 
        || el.msMatchesSelector || el.oMatchesSelector;
    for (var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for (var r in rules) {
            if (el.matches(rules[r].selectorText)) {
                ret.push(rules[r].cssText);
            }
        }
    }
    return ret;
}

JSFiddle: http://jsfiddle.net/HP326/6/

Calling css(document.getElementById('elementId')) will return an array with an element for each CSS rule that matches the passed element.
If you want to find out more specific information about each rule, check out the CSSRule object documentation.

Leave a Comment