Description:
The jQuery height() method is used to GET/SET the height for the selected element. In simple, height() method can be split in to two purposes
- GET height: It will return the height for the selected/matched element
- SET height: It will set the height for the selected/matched element
Syntax
- $(selector).height()
- $(selector).height(value)
- $(selector).height(function(index,currentheight))
Value | It specifies the height in px, pt, em, etc. In default it treat as px. |
function(index,currentclass) | A function that returns one or more class names to remove index : Returns the index position of the matched element currentclass : Returns the current class name of the matched element |
Difference between .css(“height”) & .height():
.css( “height” ) : It will returns with unit value (for example, 200px)
.height() : It return with units less (for example, 200).
When to use?
If we need to perform some mathematical calculation based on the element’s height then we can use .height().
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <style> .defaultClass { border: 5px solid #eed5b7; padding: 10px; width: 50px; height: 50px; background-color: red; display:inline-block; } </style> <script type="text/javascript"> $(document).ready(function () { $('.btnClass').click(function () { $('.defaultClass').height(20).css({ backgroundColor: '#4cff00' }) $('#divCurrentHeight').text(" Current Div height is: "+ $('.defaultClass').height()); }) }); </script> </head> <body> <button class="btnClass" id="addMethod">SET/GET height() CSS property</button><br/><br /> <div id="divbox1" class="defaultClass"> </div> <div id="divbox2" class="defaultClass"> </div> <br /><br /> <div id="divCurrentHeight"></div> </body> </html> |
Output:
Clicking on button, the .height(20) method will set height as 20 for the selected element and .height() method will GET the height of the selected div .