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.
This question is related to
javascript
jquery
html
css
Use height()
:
var result = $("#myDiv").height();
alert(result);
This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.
If you want to do it without jQuery, you can use plain JavaScript:
var result = document.getElementById("myDiv").offsetHeight;
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;_x000D_
document.getElementById("data_box").innerHTML = "height: " + innerBox;
_x000D_
body {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.relative {_x000D_
width: 220px;_x000D_
height: 180px;_x000D_
position: relative;_x000D_
background-color: purple;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 30px;_x000D_
left: 20px;_x000D_
background-color: orange;_x000D_
padding: 30px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#myDiv {_x000D_
margin: 20px;_x000D_
padding: 10px;_x000D_
color: red;_x000D_
font-weight: bold;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
#data_box {_x000D_
font: 30px arial, sans-serif;_x000D_
}
_x000D_
Get height of <mark>myDiv</mark> in px dimension:_x000D_
<div id="data_box"></div>_x000D_
<div class="relative">_x000D_
<div class="absolute">_x000D_
<div id="myDiv">myDiv</div>_x000D_
</div>_x000D_
</div>
_x000D_
Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:
javascript:
var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;
or in jquery:
$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();
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.
Source: Stackoverflow.com