I have the following elements in a HTML page:
<body>
<div style="height:100%; width:100%">
<div style="height:100px;"></div>
<div id="container" style="height:25%; width:50%">
</div>
Now I would like to get the height in pixels of the div container using jQuery (or plain JavaScript).
How can I do it?
$('#container').height() // returns `0`
In CSS, height as a percentage doesn’t work unless the parent element also has height defined. And the parent’s height won’t work (if it’s a percentage) unless its parent has height defined, and so on.
In this case, try adding this to your CSS:
Update: The other reason your code is returning
0is because the DIV doesn’t have any children (not even text nodes). If you added a child node, it would return the height of that child node, but it still wouldn’t return the 25% value until you add an explicit height to all parents of elements that define height in percentages.