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.
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).
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.
var clientHeight = document.getElementById('myDiv').clientHeight;
or
var offsetHeight = document.getElementById('myDiv').offsetHeight;
clientHeight
includes padding.
offsetHeight
includes padding, scrollBar and borders.
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}`); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With