Morvael Morvael - 4 months ago 14
HTML Question

Get actual content height with Javascript (or jQuery)

There are many ways of getting the height of a document, but due to different browser implementations most of them (I believe) return the highest of a number of values ... which is fine most of the time.

In my case I have a number of elements on the page that I know to be a smaller height than the window and viewport heights. What I'm trying to get is the actual height of all the rendered elements.

Things that don't work (with testing in Firefox):

  1. $(document).height(); // gives the window height

  2. document.body.scrollHeight; // gives 7, its always 7 I don't know why

  3. document.body.offsetHeight; // also gives 7

  4. document.documentElement.clientHeight; // sometimes gives window height

  5. document.documentElement.scrollHeight; //gives window height

  6. document.documentElement.offsetHeight; generally gives a value in the range of 23

At present I'm thinking that the way around this might be to insert a
height: 0
at the bottom of my page and grab
, but I feel that this is highly likely to go wrong at some point in the future.

So before I do that ...

Is there a way of knowing the content height when it's less than the window height?


People have asked for clarification. Heres a jsFiddle example of what I want / the results I'm getting.

Running that results in the same value for Win Height: and Doc Height being written out to the console.


My issue was due to the body not wrapping the content correctly due to floated and absolutely positioned elements, as pointed out by @tim-vermaelen in the comments to his solution.


I suggest you use $(document.body).height().

In CSS you have to put:

body { height: 100%; }

This will only give correct results in case of body padding, margin and borders of the body element are 0. When direct children are floating or put on position absolute, the height of these elements doesn't count. Hence for floating elements you always clearfix the parent to solve these wrapping issues.

If not you can use $(document.body).outerHeight(includeMargin)