Javascript DOM document object provides the getElementById method that can get the height of the Div element using its onclick event. There are two types of properties to get the height of <div> tag. offsetHeight and clientHeight are the properties that can be accessed using getElementId of the javascript document object.
Difference between offsetHeight and clientHeight property
Both properties have a difference in the value returned as the height of the specified <div> tag:
offsetHeight
offsetHeight property of getElementById method gets the height of the div element that is specified in the CSS class style.
clientHeight
clientHeight property of getElementById method gets the inner absolute height of the div element. That means if overflow CSS property of the div element is defined with value scroll then clientHeight will return the height of the div approximately 16 pixels less than the offsetHeight i.e. value of CSS height property.
Javascript Syntax to get Height of Div
document.getElementById("id").clientHeight
document.getElementById("id").offsetHeight
Javascript Code to get Height of Div onclick
<html>
<head>
<title>Javascript Get Div clientHeight and offsetHeight</title>
<style type="text/css">
#div1 {
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
<script
language="javascript"
type="text/javascript">
<![CDATA[
function getDivHeight() {
alert("Client Height: "
+ document.getElementById("div1").clientHeight);
alert("Offset Height: "
+ document.getElementById("div1").offsetHeight);
}
]]>
</script>
</head>
<body>
<center>
<div id="div1">
Get Div Height using Javscript function. Javascript DOM document can access the
height of HTML Div element dynamically.
</div>
<br />
<input type="button"
value="Get Div Height"
onclick="getDivHeight()" />
</center>
</body>
</html>
Similarly you can get the width of Div tag, see example here: Javascript Get Width of Div onclick. You can use both values i.e. width and height to dynamically expand the size of div tag.
Continue to next tutorial: Javascript Get Width of Div onclick to learn how to retrieve the width of HTML div element programatically.