Get div height with plain JavaScript

2022-08-29 23:33:52

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 , but it returned nothing, even when my div had its and set in CSS.myDiv.style.heightwidthheight


答案 1
var clientHeight = document.getElementById('myDiv').clientHeight;

or

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

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.


答案 2

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}`);
}