height()

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.

Note
The before() and insertBefore() both methods are used to perform same task. The main difference between them is in syntax, and the placement of the content and the target.

Syntax:

To return the height:

snippet
$(selector).height()

To set the height:

snippet
$(selector).height(value)

To set the height by using a function:

snippet
$(selector).height(function(index,currentheight))

Parameters of jQuery height() method

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.
  • Index:It provides the index position of the element in the set.
  • currentHeight: It provides the current height of the selected element.

Example of jQuery height() method

Let's take an example to demonstrate the jQuery height() method.

To return Height:

snippet
<!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>

jQuery height() example 2

To set height:

This example will show how to set a specific height.

snippet
<!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>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +