Retrieve CSS property from StyleSheet
Demonstration of retrieving a StyleSheet property value directly from a StyleSheet. Not recommended because of many ways this can fail. Better to create a DOM element and ask the browser for its rendered value.
by OldPro
CSS
.box{
position:absolute;
background-color:red;
height:10px;
width:10px;
}
#car, .car {
position:absolute;
background-color:red;
height:11px;
width:10px;
}
}
JavaScript
// document.styleSheets[1].cssRules[0].style['height']
function getStyleSheetPropertyValue(selectorText, propertyName) {
// search backwards because the last match is more likely the right one
for (var s= document.styleSheets.length - 1; s >= 0; s--) {
var cssRules = document.styleSheets[s].cssRules ||
document.styleSheets[s].rules || []; // IE support
for (var c=0; c < cssRules.length; c++) {
if (cssRules[c].selectorText === selectorText)
return cssRules[c].style[propertyName];
}
}
return null;
}
alert('box: '+ getStyleSheetPropertyValue('.box', 'height') + ', car: ' + getStyleSheetPropertyValue('#car, .car', 'height'))