How to get height of <div> in px dimension

Viewed 188732

I have used jQuery library to find out height of a div.

Below is my div element with attributes :

<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test</DIV>

Below is my jQuery code to get height of <div>

var result = $("#myDiv").css('height');
alert(result);

After executing above statement I am getting result as "auto". Actually this is I am not expecting, instead of that I want the result in px dimension.

5 Answers

For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

There is a built-in method to get the bounding rectangle: Element.getBoundingClientRect.

The result is the smallest rectangle which contains the entire element, with the read-only left, top, right, bottom, x, y, width, and height properties.

See the example below:

let innerBox = document.getElementById("myDiv").getBoundingClientRect().height;
document.getElementById("data_box").innerHTML = "height: " + innerBox;
body {
  margin: 0;
}

.relative {
  width: 220px;
  height: 180px;
  position: relative;
  background-color: purple;
}

.absolute {
  position: absolute;
  top: 30px;
  left: 20px;
  background-color: orange;
  padding: 30px;
  overflow: hidden;
}

#myDiv {
  margin: 20px;
  padding: 10px;
  color: red;
  font-weight: bold;
  background-color: yellow;
}

#data_box {
  font: 30px arial, sans-serif;
}
Get height of <mark>myDiv</mark> in px dimension:
<div id="data_box"></div>
<div class="relative">
  <div class="absolute">
    <div id="myDiv">myDiv</div>
  </div>
</div>

Related