We can use JavaScript to get the height of an element by using the offsetHeight property.

document.getElementById("div2").offsetHeight;

You can also get the height of an element using the height property, but one problem we see a lot is if no height is set for the element, nothing will be returned for height. This is why we prefer to always use the offsetHeight property to get the height of an element. Also, note that the offsetHeight property will return the height of the element plus any padding and/or border-width that might be added to the element.


Let’s say we have the following HTML:


This paragraph is in a div that we want to get the height of.

If we want to get the height of #div1 with padding, we would use the offsetHeight property;

document.getElementById("div1").offsetHeight;

Getting the height of an element can also be done using jQuery with the height() and outerHeight() methods.

Using JavaScript to Get and Change the Height of an Element

In the example below, we will create a div and the ability to add as many paragraphs as we want to the div. Each time we add a new paragraph to the div, it will increase the height of the div. We will then let the user check the height of the div whenever they want. Here is the initial HTML setup:


This is some text.
Add text
Get Height

We can utilize both an onclick event and the innerHTML property to add new text to #div2.

Then we can use the offsetHeight property to get the height value of #div2. Finally, we will use the textContent property to display the new height results.

Here is the code:

function addText(){
  var currHTML = document.getElementById("div2").innerHTML;
  currHTML += '
This is some more text.
' document.getElementById("div2").innerHTML = currHTML; }; function getHeight(){ var height1 = document.getElementById("div2").offsetHeight; document.getElementById("results").textContent = height1; };

The final code and output for this example is below:

Code Output:

This is some text.

Add text
Get Height

Full Code:


This is some text.
Add text
Get Height
<script> function addText(){ var currHTML = document.getElementById("div2").innerHTML; currHTML += '
This is some more text.
'; document.getElementById("div2").innerHTML = currHTML; }; function getHeight(){ var height1 = document.getElementById("div2").offsetHeight; document.getElementById("results").textContent = height1; }; </script>

Hopefully this article has helped you understand how to use JavaScript to get the height of an element.

Categorized in:

JavaScript,

Last Update: February 26, 2024