I have elements with an external style of height with percentages. when I am trying to save the height as a variable to use, it is saving it as pixels some times nothing.
html For example:
<div id='firstDiv'></div>
<div id='secondDiv'></div>
css code
#firstDiv{
width:50%;
height:50%;
}
#secondDiv{
width:20%;
height:50%;
}
Jquery code
$('div').each(function (){
console.log($(this)[0].style.height);
}
how can i get it as %?
To get the value in %, you can divide the value with either the top most node [1st parent in dom]
parseFloat($(this)[0].style.height / $('#idOfFirstParent').height ()) * 100;
, if you want to get the value in reference to the 1st parent in the DOM or by width of the document [this will start with 0,0 of your screen].
(parseFloat($(this)[0].style.height/ $('window').height ()) * 100).toFixed(2);
or
(parseFloat($(this)[0].style.height / $('document').height ()) * 100).toFixed(2);
Try this, not direct option in jQuery.
var height = ( 100 * parseFloat($(element).css('height')) / parseFloat($(element).parent().css('height')) ) + '%';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With