Search code examples
javascriptcssprototypejs

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?


Solution

  • 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;
         }
    }