The jQuery height() method is used to return the current computed height for the first element or set the height of every matched element. In other words, you can say that the height() method is used for two purposes:
To return height: When this method is used to return height, it returns the height of first matched element.
To set height: When this method is used to set height, it sets height of all matched elements.
This method is a very common jQuery dimension.
Syntax:
To return the height:
$(selector).height()
To set the height:
$(selector).height(value)
To set the height by using a function:
$(selector).height(function(index,currentheight))
Parameter | Description |
---|---|
Value | This is a mandatory parameter. It specifies the height in px, em, pt, etc. its defauly unit is px. |
Function (index, currentHeight) | This is an optional parameter. This is used to specify a function that returns the new height of the selected element.
|
Let's take an example to demonstrate the jQuery height() method.
To return Height:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert("Height of div: " + $("div").height()); }); }); </script> </head> <body> <div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid blue;background-color:lightpink;"><div class="div">Hello Guys!<br/> This is rookienerd.com</div></div><br> <button>Display the height of div</button> </body> </html>
To set height:
This example will show how to set a specific height.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>height demo</title> <style> div { width: 50px; height: 100px; float: left; margin: 5px; background: rgb(255,140,0); cursor: pointer; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <script> $( "div" ).one( "click", function() { $( this ).height( 50 ).css({ cursor: "auto", backgroundColor: "green" }); }); </script> </body> </html>