tags:

views:

1051

answers:

4

Let's say the rule is as follows:

.largeField {
    width: 65%;
}

Is there a way to get '65%' back somehow, and not the pixel value?

Thanks.

EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.

This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).

+3  A: 

There's no built-in way, I'm afraid. You can do something like this:

var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
Adam Lassek
A: 

You could put styles you need to access with jQuery in either:

  1. the head of the document directly
  2. in an include, which server side script then puts in the head

Then it should be possible (though not necessarily easy) to write a js function to parse everything within the style tags in the document head and return the value you need.

wheresrhys
+5  A: 

You could access the document.styleSheets object:

<style type="text/css">
    .largeField {
        width: 65%;
    }
</style>
<script>
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var i=0; rules.length; i++) {
        var rule = rules[i];
        if (rule.selectorText.toLowerCase() == ".largefield") {
            alert(rule.style.getPropertyValue("width"));
        }
    }
</script>
Gumbo
+1 proper usage of DOM methods (sometimes jQuery is not the answer)
bobince
+1 I'm with you here for accuracy. I'm curious about how each browser suppports this, but this is the right answer.
altCognito
Works well in simpler cases, both FF and IE7, but not for me (see EDIT above).
dalbaeb
Have you tried running through all stylesheets too? My example just used the first (`styleSheets[0]`).
Gumbo
A: 

You can use the css(width) function to return the current width of the element.

ie.

var myWidth = $("#myElement").css("width");

See also: http://api.jquery.com/width/ http://api.jquery.com/css/