To set the height of a div in jQuery we can do this easily by using the jQuery height() method.
$("#div1").height(100);
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 jQuery height() method in the following JavaScript code.
$("#div1").height(200);
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").height(200);
Example of Using jQuery 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 jQuery click() method to run a function when a user enters a new height.
We can use the val() method to get the new height the user has entered. We will then use the height() method to set the new height to #div2, based on what the user has entered.
Here is the code:
$("#click-me").click(function(){
//Get the new height the user has entered
var newHeight = Number($('#new-height').val());
//Set the new height of #div
$('#div2').height(newHeight);
});
The final code and output for setting the height of a div using jQuery is below:
Code Output:
Enter a new height below:
Full Code:
Enter a new height below:
Change height
<script>
$("#click-me").click(function(){
var newHeight = Number($('#new-height').val());
$('#div2').height(newHeight);
});
</script>
Hopefully this article has helped you to understand how to set the height of div using jQuery.