get CSS rule's percentage value in jQuery
Solution 1:
Most easy way
$('.largeField')[0].style.width
// >>> "65%"
Solution 2:
This is most definitely possible!
You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.
$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);
See my example.
Now... I wonder if I'm first to discover this hack:)
Update:
One-liner
element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
It will leave behind a hidden element before the </body>
tag, which you may want to .remove()
.
See an example of one-liner.
I'm open to better ideas!
Solution 3:
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')) ) + '%';
Solution 4:
You could access the document.styleSheets
object:
<style type="text/css">
.largeField {
width: 65%;
}
</style>
<script type="text/javascript">
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var i=0; i < rules.length; i++) {
var rule = rules[i];
if (rule.selectorText.toLowerCase() == ".largefield") {
alert(rule.style.getPropertyValue("width"));
}
}
</script>