Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Prototype: Get css values, without referencing DOM elements?

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?

like image 781
user76568 Avatar asked Dec 18 '13 13:12

user76568


2 Answers

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

like image 112
Greg Burghardt Avatar answered Nov 13 '22 07:11

Greg Burghardt


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;
     }
}
like image 41
adeneo Avatar answered Nov 13 '22 07:11

adeneo