How do you get the rendered height of an element?
Let's say you have a <div>
element with some content inside. This content inside is going to stretch the height of the <div>
. How do you get the "rendered" height when you haven't explicitly set the height. Obviously, I tried:
var h = document.getElementById('someDiv').style.height;
Is there a trick for doing this? I am using jQuery if that helps.
Definitely use
or
I'm posting this as an additional answer because theres a couple important things I just learnt.
I almost fell into the trap just now of using offsetHeight. This is what happened :
Here's just a portion of it :
Yup it looks at BOTH scroll and offset. If that fails it looks even further, taking into account browser and css compatibility issues. In other words STUFF I DONT CARE ABOUT - or want to.
But I dont have to. Thanks jQuery!
Moral of the story : if jQuery has a method for something its probably for a good reason, likely related to compatibilty.
If you haven't read through the jQuery list of methods recently I suggest you take a look.
Hm we can get the Element geometry...
How about this plain JS ?
offsetHeight
, usually.If you need to calculate something but not show it, set the element to
visibility:hidden
andposition:absolute
, add it to the DOM tree, get theoffsetHeight
, and remove it. (That's what the prototype library does behind the scenes last time I checked).If you are using jQuery already, your best bet is
.outerHeight()
or.height()
, as has been stated.Without jQuery, you can check the box-sizing in use and add up various paddings + borders + clientHeight, or you can use getComputedStyle:
var h = getComputedStyle(document.getElementById('someDiv')).height;
h
will now be a string like a "53.825px".And I can't find the reference, but I think I heard
getComputedStyle()
can be expensive, so it's probably not something you want to call on eachwindow.onscroll
event (but then, neither is jQuery'sheight()
).You can use
.outerHeight()
for this purpose.It will give you full rendered height of the element. Also, you don't need to set any
css-height
of the element. For precaution you can keep its height auto so it can be rendered as per content's height.For a clear view of these function you can go for jQuery's site or a detailed post here.
it will clear the difference between
.height()
/innerHeight()
/outerHeight()
With MooTools:
$('someDiv').getSize().y