Query property value of a css class even if not in use

I have a situation where I would like to know the value of the 'width' property of a css class defined as 'foo' (eg: ".foo { width:200px}" ).

However, there may not actually exist (yet) an element with said class in the dom.

I want to be able to access this value from Javascript (to calculate percentages of other divs for setting a complex layout).

I am pretty sure the answer is that this is probably not possible, but I think it would be a really useful feature and would enable design/layout properties to be effectively defined in CSS.

Is there any way to do this? (without hacks like rendering divs offscreen, then querying their class properties).

Perhaps it could be implemented as a standard browser javascript library - possibly a document.styles object? thus, my property could be found from within javascript as: "document.styles.foo.width" - How do I submit a proposal to the w3c?

Answers:

Answer

A solution would be to create an element and not add it to the document.

But there is a cleaner solution as in javascript you can easily iterate over stylesheets and their content :

for (var i=0; i<document.styleSheets.length; i++) {
    var styleSheet = document.styleSheets[i];
    var cssRules = styleSheet.rules; // chrome, IE
    if (!cssRules) cssRules = styleSheet.cssRules; // firefox
    for (var ir=cssRules.length; ir-->0;) {
        var rule = this.cssRules[ir];
        if (rule.selectorText==".foo") {
              var width = parseInt(rule.style.getPropertyValue('width'), 10);
              // do what you want

        }
    }
}

As you're iterating on a yet parsed structure, this is an efficient solution.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.