The jQuery height() method can be used to get or set the height of the selected element. It can be useful when you want to check the height of the elements.
If the element already has a height, it overwrites the height with the specified height value. It will not check the padding, border, and margin of the selected element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters are given below.
Parameter Name | Description |
---|---|
selector | Specify the selector to select the elements and return or sets the height. You can tag name, class name, or id of the elements to select. |
value | It is the value of the height you set for the selected element. It can be in px, em, etc. |
index | It returns the index position of the selected element. |
current_height | It returns the current height of the selected element. |
jQuery height() Method to Get or Return the Value of Height
If you want to get the height of the selected element, you can use this method. It returns the height already present in the selected element. The below example contains the div element with height and width. The method returns the height and displays the height in the alert box.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> $(document).ready(function(){ $('.mygetbtn').click(function(){ var mydivht = $(".divht").height(); alert(mydivht); }); }); </script> <style> .divht{ width:100px; height:100px; border:1px solid #ccc; } </style> <button type="button" class="mygetbtn">Click to Return Height</button><br><br> <div class="divht"></div> |
Output
You have to click the button given above to get the height of the element. An alert box showing the height of the selected element.
Set the Height of an Element Using the Method
The jQuery height() method can be used to set the height of the element. To set the height, you have to specify the height in px, em, etc. The div element already has a height in px which gets overwritten with the specified one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $(".divsetht").height("150"); }); }); </script> <style> .divsetht{ width:100px; height:100px; border:1px solid #ccc; } </style> <button type="button" class="mysetbtn">Click to Set Height</button><br><br> <div class="divsetht"></div> |
Output
When you click the button given above, the method changes the height of the element with the specified height. You can find the difference after you click on the button element.
You may also like to read
I hope you like this tutorial on jQuery height() method. If you have any queries regarding the tutorial, please comment below.
References