How do you read CSS rule values with JavaScript?

Adapted from here, building on scunliffe’s answer:

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

alert(getStyle('.test'));

Leave a Comment