To set the height of a div in JavaScript we can do this easily by using the Style height Property.

document.getElementById("div1").style.height = "100px";

Let’s take a look at a simple example below.


Let’s say we have the following HTML:

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

If we want to set the height of #div1 to say 200px, we will use the height Property in the following JavaScript code.

document.getElementById("div1").style.height = "200px";

We can also set the height of a div using jQuery with the jQuery height() method.

Example of Using JavaScript to Set the Height of a Div

In this example, we will have a simple div with a background color. The height of the div will be 100px. We will have an input field that will allow the user to enter a new height for the div. Here is the HTML code.


Enter a new height below:

Change height

We can utilize the onclick event to run a function when a user enters a new height.

We can also use the value property to get the new height the user has entered. We will then use the height Property to set the new height to #div2, based on what the user has entered.

Here is the code:

function changeHeight(){
  //Get the new height the user has entered
  var newHeight = Number(document.getElementById("new-height").value) + "px";

  //Set the new height of #div
  document.getElementById('div2').style.height = newHeight;
};

The final code and output for setting the height of a div using JavaScript is below:

Code Output:

Enter a new height below:

Change height

Full Code:


Enter a new height below:

Change height
<script> function changeHeight(){ var newHeight = Number(document.getElementById("new-height").value) + "px"; document.getElementById('div2').style.height = newHeight; }; </script>

Hopefully this article has helped you to understand how to set the height of div using JavaScript.

Categorized in:

JavaScript,

Last Update: February 26, 2024