Is it possible to retrieve a style property by class name (e.g width of a class), defined in a CSS file, without having to fetch it from an actual element in the DOM?
Yes. Check out the document.styleSheets
property.
https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets
http://www.quirksmode.org/dom/tests/stylesheets.html
It is indeed possible, but more complicated.
You have access to stylesheets with the document.styleSheets
property.
Within each stylesheet you have to access to the cssRules property that contains all the CSS rules in that stylesheet, so to get the first rule in the first stylesheet in the DOM you can do
document.styleSheets[0].cssRules[0];
To find a certain element you have to parse the stylesheet, and this is where it get's complicated in some cases, as styles are inherited etc. but if looking for a certain selector and a certain style :
var rules = document.styleSheets[0].cssRules,
theRule = null;
for (var i=0; i<rules.length; i++) {
if (rules[i].selectorText.toLowerCase() == '#myelement') {
var width = rules[i].style.width;
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With