Diodeus Diodeus - 1 month ago 5
CSS Question

How do you read CSS rule values with JavaScript?

I would like to return a string with all of the contents of a CSS rule, like the format you'd see in an inline style. I'd like to be able to do this without knowing what is contained in a particular rule, so I can't just pull them out by style name (like

.style.width
etc.)

The CSS:

.test {
width:80px;
height:50px;
background-color:#808080;
}


The code so far:

function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')

Answer

Adapted from here, building on scunliffe's answer:

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