[ACCEPTED]-get CSS rule's percentage value in jQuery-css
Most easy way
$('.largeField')[0].style.width
// >>> "65%"
0
This is most definitely possible!
You must 7 first hide() the parent element. This will 6 prevent JavaScript from calculating pixels 5 for the child element.
$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);
See my example.
Now... I wonder 4 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 3 leave behind a hidden element before the 2 </body>
tag, which you may want to .remove()
.
See an example of one-liner.
I'm 1 open to better ideas!
There's no built-in way, I'm afraid. You 1 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>
0
Late, but for newer users, try this if the css style contains a percentage:
$element.prop('style')['width'];
0
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 4 return '65%'. Only returns rounded numbers 3 to work better if you do like if (width=='65%'). If 2 you would have used Adams answer directly, that 1 hadn't worked (I got something like 64.93288590604027). :)
Building on timofey's excellent and surprising 2 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 1 it's helpful to someone.
I have a similar issue in Getting values of global stylesheet in jQuery, eventually I 3 came up with the same solution as above.
Just wanted to crosslink 2 the two questions so others can benefit 1 from later findings.
Convert from pixels to percentage using cross multiplication.
Formula Setup:
1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage 2 / 100)
2.) element_width_percentage = (100 1 * element_width_pixels) / parent_width_pixels
The actual code:
<script>
var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
</script>
A late response but wanted to add on for 15 anyone 2020+ who stumbles across this. Might 14 be more for niche cases but I wanted to 13 share a couple options.
If you know what 12 the initial % value is you can also assign 11 these values to variables in the :root of 10 the style sheet. i.e
:root {
--large-field-width: 65%;
}
.largeField {
width: var(--large-field-width);
}
When you want to access 9 this variable in JS you then simply do the 8 following:
let fieldWidth = getComputedStyle(document.documentElement).getPropertyValue('--large-field-width');
// returns 65% rather than the px value. This is because the % has no relative
// size to the root or rather it's parent.
The other option would be to assign 7 the default styling at the start of your 6 script with:
element.style.width = '65%'
It can then be accessed with:
let width = element.style.width;
I 5 personally prefer the first option but it 4 really does depend on your use case. These 3 are both technically inline styling but 2 I like how you can update variable values 1 directly with JS.
You could put styles you need to access 5 with jQuery in either:
- the head of the document directly
- in an include, which server side script then puts in the head
Then it should be 4 possible (though not necessarily easy) to 3 write a js function to parse everything 2 within the style tags in the document head 1 and return the value you need.
There's nothing in jQuery, and nothing straightforward 3 even in javascript. Taking timofey's answer 2 and running with it, I created this function 1 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
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.