Tutorials using JS
Get height of a div using JavaScript
In this tutorial, you shall learn how to get the height of a div element using JavaScript.
Solution
To get the height of a div element using JavaScript, we can read either of the three following properties based on the inclusion of padding, borders, or scrolling height.
divElement.clientHeight //height + vertical padding
divElement.offsetHeight //height + vertical padding + vertical borders
divElement.scrollHeight //height of contained doc + vertical padding
Program
When user clicks on the Click me
button, we get the div element with the id myDiv
, and then display the clientHeight
, offsetHeight
, and scrollHeight
of the div in console.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<div id="myDiv" class="card tile active">About</div>
<p id="output"></p>
<style>
#myDiv {
margin: 10px;
padding : 5px;
width: 100px;
height: 100px;
}
</style>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get div element
const myDiv = document.getElementById("myDiv");
//display different heights of div
document.getElementById("output").innerHTML += myDiv.clientHeight + '<br>';
document.getElementById("output").innerHTML += myDiv.offsetHeight + '<br>';
document.getElementById("output").innerHTML += myDiv.scrollHeight;
});
</script>
</body>
</html>