Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get div height with plain JavaScript

Any ideas on how to get a div's height without using jQuery?

I was searching Stack Overflow for this question and it seems like every answer is pointing to jQuery's .height().

I tried something like myDiv.style.height, but it returned nothing, even when my div had its width and height set in CSS.

like image 967
lwiii Avatar asked Mar 25 '13 12:03

lwiii


People also ask

What is offsetHeight in JavaScript?

The HTMLElement. offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).

How do I get jquery clientHeight?

clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present). I'm assuming that is the scrollbar of the element itself, not the entire browser window, unless the element takes up the entire window.


2 Answers

var clientHeight = document.getElementById('myDiv').clientHeight; 

or

var offsetHeight = document.getElementById('myDiv').offsetHeight; 

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.

like image 59
Dan Avatar answered Sep 29 '22 06:09

Dan


Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

Example:

var elem = document.getElementById("myDiv"); if(elem) {   var rect = elem.getBoundingClientRect();   console.log("height: " + rect.height);   } 

UPDATE: Here is the same code written in 2020:

const elem = document.querySelector("#myDiv"); if(elem) {   const rect = elem.getBoundingClientRect();   console.log(`height: ${rect.height}`); } 
like image 28
user4617883 Avatar answered Sep 29 '22 05:09

user4617883