jQuery get the rendered height of an element?
Asked Answered
P

18

455

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.

Petrapetracca answered 8/2, 2009 at 20:49 Comment(1)
see this answer #19581807Thorvaldsen
N
202

It should just be

$('#someDiv').height();

with jQuery. This retrieves the height of the first item in the wrapped set as a number.

Trying to use

.style.height

only works if you have set the property in the first place. Not very useful!

Nonreturnable answered 8/2, 2009 at 20:52 Comment(7)
even if you're NOT using jQuery or cant or don't want to I strongly suggest anyone implementing this by using just offsetHeight goes ahead and downloads the jQuery source and searches for "height" to find the code they use. lots of crazy stuff going on in there !Hagfish
Absolutely agree with that Simon. It's always insightful to investigate how Javascript libraries accomplish a solution to a problemNonreturnable
@matejkramny - This question and answer was over 5 years ago. The OP was already using jQuery on their site so rather than re-implement the same/similar logic him/herself, why not use the one line jQuery function that already does it? I'd agree that jQuery is overkill for a lot of things and I'm not afraid of vanilla JS, but when there is a function in a library that does exactly what you need, it seems silly not to use it, particularly for reasons of "Not Invented Here"Nonreturnable
@RussCam Ok thats a good point.. I would add that it doesn't help you (or the random visitor) learn what actually happens behind the scenes. Too many answers provide one-line 'jquery' solution that yes, works, however it doesn't educate anybody in terms of what happens with the DOM and how it worksCracksman
@matejkramny The OPs intention when asking the question was to get the rendered height of the element, not to understand what's happening in the DOM and behind the scenes; if that was their intention, they asked the wrong question. I agree that people should be inclined to understand the libraries and frameworks they use, knowledge is power and all that, but sometimes one just wants an answer to a specific question. Indeed, the above comments already suggest looking through the jQuery code to understand what's going on behind the scenes.Nonreturnable
For the OP, using jQuery is a valid answer. For the rest of the world seeing this from then on, the non-jQuery answer is the best one. Perhaps SO needs to adapt to that reality, maybe highest voted answers should be highlighted in some way more than accepted ones.Hanuman
This doesn't return the value in px when the height is set in % (e.g. 100%). The other answer, document.getElementById('someDiv').getBoundingClientRect().height returns the correct value in px.Redcap
L
1303

Try one of:

var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

Lefkowitz answered 8/2, 2009 at 20:51 Comment(6)
Thanks, I didn't know about this property. It is IE8+ compatible also.Pyrometer
I'm perplexed with the meaning of clientHeight. I have a div element which has a bunch of p elements in it and the content goes far beyond the viewable area of the browser downward. And I expected clientHeight to give the rendered height, and scrollHeight to give the full length. But they are almost equal ( only differing by margin, padding etc.) .Barbrabarbuda
@Barbrabarbuda unless it itself has a limited height and an overflow:hidden or some form of overflow:scroll, the element will expand (whether in your view or not) to show all the content and scrollHeight and clientHeight will be equal.Hypophosphite
Great answer, but logically, the borders that affect the height of an element are the top and bottom borders, which are horizontal. This answer refers to them as "vertical borders." Just thought I'd drop my 2 centsLenhart
From what I know, .clientWidth/.clientHeight do NOT include scroll width if scroll is shown. If you want scroll width to be included, can use element.getBoundingClientRect().width insteadProfluent
scrollHeight does not include borders, please see MDN developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeightGoethe
N
202

It should just be

$('#someDiv').height();

with jQuery. This retrieves the height of the first item in the wrapped set as a number.

Trying to use

.style.height

only works if you have set the property in the first place. Not very useful!

Nonreturnable answered 8/2, 2009 at 20:52 Comment(7)
even if you're NOT using jQuery or cant or don't want to I strongly suggest anyone implementing this by using just offsetHeight goes ahead and downloads the jQuery source and searches for "height" to find the code they use. lots of crazy stuff going on in there !Hagfish
Absolutely agree with that Simon. It's always insightful to investigate how Javascript libraries accomplish a solution to a problemNonreturnable
@matejkramny - This question and answer was over 5 years ago. The OP was already using jQuery on their site so rather than re-implement the same/similar logic him/herself, why not use the one line jQuery function that already does it? I'd agree that jQuery is overkill for a lot of things and I'm not afraid of vanilla JS, but when there is a function in a library that does exactly what you need, it seems silly not to use it, particularly for reasons of "Not Invented Here"Nonreturnable
@RussCam Ok thats a good point.. I would add that it doesn't help you (or the random visitor) learn what actually happens behind the scenes. Too many answers provide one-line 'jquery' solution that yes, works, however it doesn't educate anybody in terms of what happens with the DOM and how it worksCracksman
@matejkramny The OPs intention when asking the question was to get the rendered height of the element, not to understand what's happening in the DOM and behind the scenes; if that was their intention, they asked the wrong question. I agree that people should be inclined to understand the libraries and frameworks they use, knowledge is power and all that, but sometimes one just wants an answer to a specific question. Indeed, the above comments already suggest looking through the jQuery code to understand what's going on behind the scenes.Nonreturnable
For the OP, using jQuery is a valid answer. For the rest of the world seeing this from then on, the non-jQuery answer is the best one. Perhaps SO needs to adapt to that reality, maybe highest voted answers should be highlighted in some way more than accepted ones.Hanuman
This doesn't return the value in px when the height is set in % (e.g. 100%). The other answer, document.getElementById('someDiv').getBoundingClientRect().height returns the correct value in px.Redcap
Y
155

NON JQUERY since there were a bunch of links using elem.style.height in the top of these answers...

INNER HEIGHT:
https://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight

document.getElementById(id_attribute_value).clientHeight;

OUTER HEIGHT:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetHeight

document.getElementById(id_attribute_value).offsetHeight; 

Or one of my favorite references: http://youmightnotneedjquery.com/

Ygerne answered 26/1, 2015 at 17:35 Comment(0)
A
59

I use this to get the height of an element (returns float):

document.getElementById('someDiv').getBoundingClientRect().height

It also works when you use the virtual DOM. I use it in Vue like this:

this.$refs['some-ref'].getBoundingClientRect().height

For a Vue component:

this.$refs['some-ref'].$el.getBoundingClientRect().height
Adelleadelpho answered 12/9, 2018 at 11:58 Comment(1)
getBoundingClientRect().height returns a floating-point number (while the others return integer), nice :)Ose
P
51

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.

//if you need height of div excluding margin/padding/border
$('#someDiv').height();

//if you need height of div with padding but without border + margin
$('#someDiv').innerHeight();

// if you need height of div including padding and border
$('#someDiv').outerHeight();

//and at last for including border + margin + padding, can use
$('#someDiv').outerHeight(true);

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()

Pediment answered 30/1, 2013 at 9:14 Comment(0)
L
32
style = window.getComputedStyle(your_element);

then simply: style.height

Leflore answered 11/2, 2017 at 21:12 Comment(0)
H
15

Definitely use

$('#someDiv').height()   // to read it

or

$('#someDiv').height(newHeight)  // to set it

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 :

  • I used the good old trick of using a debugger to 'watch' what properties my element has
  • I saw which one has a value around the value I was expecting
  • It was offsetHeight - so I used that.
  • Then i realized it didnt work with a hidden DIV
  • I tried hiding after calculating maxHeight but that looked clumsy - got in a mess.
  • I did a search - discovered jQuery.height() - and used it
  • found out height() works even on hidden elements
  • just for fun I checked the jQuery implementation of height/width

Here's just a portion of it :

Math.max(
Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
Math.max(document.body["offset" + name], document.documentElement["offset" + name])
) 

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.

Hagfish answered 13/2, 2009 at 3:55 Comment(1)
Saw your other comment at the question level. I'm sold on jQuery. Have been for a little while. But this sealed the deal. I'm in love with the fact this simple thing is going to solve 100s of layout issues for me (mostly on Intranet sites where I know JavaScript is running).Petrapetracca
I
14

I think the best way to do this in 2020 is to use vanilla js and getBoundingClientRect().height;

Here's an example

let div = document.querySelector('div');
let divHeight = div.getBoundingClientRect().height;

console.log(`Div Height: ${divHeight}`);
<div>
  How high am I? 🥴
</div>

On top of getting height this way, we also have access to a bunch of other stuff about the div.

let div = document.querySelector('div');
let divInfo = div.getBoundingClientRect();

console.log(divInfo);
<div>What else am I? 🥴</div>
Inveigle answered 6/1, 2020 at 11:43 Comment(1)
What does client in the method name mean?Outstay
V
13

I made a simple code that doesn't even need JQuery and probably gonna help some people. It gets the total height of 'ID1' after loaded and use it on 'ID2'

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

Then just set the body to load it

<body onload='anyName()'>
Vestibule answered 31/7, 2012 at 13:55 Comment(0)
M
13
document.querySelector('.project_list_div').offsetHeight;
Microprint answered 20/8, 2018 at 10:0 Comment(1)
This property will round the value to an integer. If you need a float value, use elem.getBoundingClientRect().heightKacey
G
11

Hm we can get the Element geometry...

var geometry;
geometry={};
var element=document.getElementById(#ibims);
var rect = element.getBoundingClientRect();
this.geometry.top=rect.top;
this.geometry.right=rect.right;
this.geometry.bottom=rect.bottom;
this.geometry.left=rect.left;
this.geometry.height=this.geometry.bottom-this.geometry.top;
this.geometry.width=this.geometry.right-this.geometry.left;
console.log(this.geometry);

How about this plain JS ?

Gambell answered 24/3, 2018 at 21:19 Comment(1)
var geometry; geometry={}; can simply be var geometry={};Spirit
R
8

So is this the answer?

"If you need to calculate something but not show it, set the element to visibility:hidden and position:absolute, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."

I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.

29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.

1) clientHeight was also 0.

2) Dom actually gave me a height which was great.

3) ClientRects returns a result almost identical to the DOM technique.

Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.

I added a few snapshots to illustrate how the height is calculated differently. Menu block rendered normally Menu block added to DOM Temp element

The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!

(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.

* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!

When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.

This is illustrated in the following snapshot (taken from Chrome once working.)
enter image description here

Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.

I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.

Richardson answered 28/6, 2011 at 21:59 Comment(0)
P
6

offsetHeight, usually.

If you need to calculate something but not show it, set the element to visibility:hidden and position:absolute, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the scenes last time I checked).

Piroshki answered 13/2, 2009 at 0:5 Comment(2)
interesting. i've never checked prototype. any idea why jQuery doesn't do that behind the scenes?Hagfish
I saw that when having difficulties and tested out that technique and it worked quite well in plain JavaScriptRichardson
P
5

Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:

function getHeight(element)
{
    var e = element.cloneNode(true);
    e.style.visibility = "hidden";
    document.body.appendChild(e);
    var height = e.offsetHeight + 0;
    document.body.removeChild(e);
    e.style.visibility = "visible";
    return height;
}
Pursuit answered 1/1, 2015 at 9:4 Comment(5)
you need to clone the element otherwise it'll be removed from the dom completely it seems from your code that's what'll happen.Maye
This code is not intended to keep the element in the DOM. It is intended to put it into the DOM just briefly (long enough to render it and get its height), then it takes it out. You can later put the element into the dom elsewhere later (knowing what its height will be before you do). Notice the function name "getHeight"; that's all that the code intends to do.Pursuit
@Maye : I see what you mean. Your element is already in the dom. The code I wrote is for an element that is not yet in the DOM. Cloning would be better, as you say, because it wouldn't matter if the element is in the dom or not.Pursuit
@Maye : I modified the code use cloning, but have not tested it.Pursuit
yeah, that was my point. Seemed to me that he says "element" for an existing element in the DOM. But all good! Don't get it wrong.Maye
J
4

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 each window.onscroll event (but then, neither is jQuery's height()).

Jalapa answered 25/3, 2014 at 16:24 Comment(1)
Once you have the height from getComputedStyle, use parseInt(h, 10) to get a integer for calculations.Book
T
2

With MooTools:

$('someDiv').getSize().y

Tonie answered 13/2, 2009 at 0:9 Comment(0)
R
1

If i understood your question correctly, then maybe something like this would help:

function testDistance(node1, node2) {
    /* get top position of node 1 */
    let n1Pos = node1.offsetTop;
    /* get height of node 1 */
    let n1Height = node1.clientHeight;
    /* get top position of node 2 */
    let n2Pos = node2.offsetTop;
    /* get height of node 2 */
    let n2Height = node2.clientHeight;

    /* add height of both nodes */
    let heightTogether = n1Height + n2Height;
    /* calculate distance from top of node 1 to bottom of node 2 */
    let actualDistance = (n2Pos + n2Height) - n1Pos;

    /* if the distance between top of node 1 and bottom of node 2
       is bigger than their heights combined, than there is something between them */
    if (actualDistance > heightTogether) {
        /* do something here if they are not together */
        console.log('they are not together');
    } else {
        /* do something here if they are together */
        console.log('together');
    } 
}
Resentment answered 27/1, 2019 at 15:2 Comment(0)
H
-4

Have you set the height in the css specifically? If you haven't you need to use offsetHeight; rather than height

var h = document.getElementById('someDiv').style.offsetHeight;
Headwork answered 8/2, 2009 at 20:52 Comment(1)
offsetHeight is a property of the element itself, not of its style.Jobber

© 2022 - 2024 — McMap. All rights reserved.