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?
A jQuery plugin based on Adams answer:
(function ($) {
$.fn.getWidthInPercent = function () {
var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
return Math.round(100*width)+'%';
};
})(jQuery);
$('body').html($('.largeField').getWidthInPercent());
Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)
There's nothing in jQuery, and nothing straightforward even in javascript. Taking timofey's answer and running with it, I created this function that works to get any properties you want:
// gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
// domNode - the node to get properties for
// properties - Can be a single property to fetch or an array of properties to fetch
function getFinalStyle(domNode, properties) {
if(!(properties instanceof Array)) properties = [properties]
var parent = domNode.parentNode
if(parent) {
var originalDisplay = parent.style.display
parent.style.display = 'none'
}
var computedStyles = getComputedStyle(domNode)
var result = {}
properties.forEach(function(prop) {
result[prop] = computedStyles[prop]
})
if(parent) {
parent.style.display = originalDisplay
}
return result
}
I have a similar issue in Getting values of global stylesheet in jQuery, eventually I came up with the same solution as above.
Just wanted to crosslink the two questions so others can benefit from later findings.
Late, but for newer users, try this if the css style contains a percentage:
$element.prop('style')['width'];
Convert from pixels to percentage using cross multiplication.
Formula Setup:
1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)
2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels
The actual code:
<script>
var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
</script>
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/