Reputation: 447
I am trying to figure out a way to execute the CSS calc function directly in my js file in order to compare two elements height.
So let's say i have two elements that I get using jQuery, and all I want to do is something around those simple lines :
if (element1.height > element2.height) then ...
Element2 is nested within Element1, who has an overflow:scroll.
Problem is, my element1 has all attributes clientHeight, scrollHeight,etc equals to 0 and when i go in the element1.style.height the result is : "calc(100% - 64px)". Please do note that the result of this is never equal to 0px since my element1 height when i inspect it is around 500px (of course depends of the screen size). And my element2 height is obtained in px using element2.scrollHeight (more reliable in my case).
So in the end I'm trying to compare two expressions that would like this : calc(100% - 64px) > 452 .. And of course this doesn't work.
Is there any way I could execute the calc() function within my js file to get the equivalent height in px in order to compare my two elements ? Or can I have access to the data anywhere else ?
My end goal is to know whether the element2's height is bigger than element1's. So any other implementation that height calculation is welcome as well.
Upvotes: 4
Views: 5744
Reputation: 3958
You can get the computed style using Window.getComputedStyle(). Check out the compatibility table.
Then, grab the width
and remove the "px" from the result, and parse it to an integer:
let myElement = document.getElementById('child');
let width = parseInt(window.getComputedStyle(myElement).width.slice(0, -2), 10);
console.log(width);
#parent {
background: red;
height: 100px;
width: 80%;
}
#child {
background: green;
height: 60px;
width: calc(100% - 64px);
}
<div id="parent">
<div id="child"></div>
</div>
Upvotes: 2