Reputation: 466
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?
Upvotes: 9
Views: 806
Reputation: 318182
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;
}
}
Upvotes: 1
Reputation: 18783
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
Upvotes: 2