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?
Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:
function cssDimensions(element)
var cn = element.cloneNode();
var div = document.createElement('div');
div.appendChild(cn);
div.style.display = 'none';
document.body.appendChild(div);
var cs = window.getComputedStyle
? getComputedStyle(cn, null)
: cn.currentStyle;
var ret = { width: cs.width, height: cs.height };
document.body.removeChild(div);
return ret;
}
Hope it's helpful to someone.
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')) ) + '%';
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>
Most easy way
$('.largeField')[0].style.width
// >>> "65%"
You could put styles you need to access with jQuery in either:
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.
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:
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!