English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery Miscellaneous

jQuery HTML/CSS Methods

jQuery height() Method

first selected elementThe height() method gets or sets the height of the selected element.Getheight, it will returnof all selected elements

first selected elementWhen the height() method is usedSetWhen setting the height, it will setof all selected elements

As shown in the figure below, the height() method does not include padding, border or margin:

The height value can also be relative. If a leading+=or-=A character sequence, then calculate the target height by adding or subtracting the given value from the current value (for example height("+ = 50"))。

Syntax:

Get height:

$(selector).height()

Set height:

$(selector).height(value)

Set height using a function:

$(selector).height(function(index, currentHeight))

Example

Get the height of the DIV element:

$("div").click(function(){
  $(this).height();
});
Test to see‹/›

Set the height of all paragraphs:

$("button").click(function(){
  $("p").height(50);
});
Test to see‹/›

Set the height of all paragraphs using different units:

$("#btn1").click(function(){
  $("p").height(50);
});
$("#btn2").click(function(){
  $("p").height("7em");
});
$("#btn3").click(function(){
  $("p").height("100vh");
});
Test to see‹/›

Increase the height of all paragraphs when the button is clicked (using the function):

$("button").click(function(){
  $("p").height(function(i, val){
    return val * 2;
  });
});
Test to see‹/›

The height() method can also find the height of the window and document:

$(window).height();// Return the height of the browser window
$(document).height();  // Return the height of the HTML document
Test to see‹/›

Show the difference between width(), height(), innerHeight(), innerWidth(), outerWidth() and outerHeight():

$("button").click(function(){
  $("div").width();
  $("div").innerWidth();
  $("div").outerWidth();
  $("div").height();
  $("div").innerHeight();
  $("div").outerHeight();
});
Test to see‹/›

Add a smooth scrolling effect when the user scrolls the page:

let size = $(".main").height(); // Get the height of ".main"
$(window).keydown(function(event) {
  if(event.which === 40) { // If the down arrow key is pressed
    $("html, body").animate({scrollTop: "+=" + size}, 300);
  } else if(event.which === 38) { // If the up arrow key is pressed
    $("html, body").animate({scrollTop: "-=" + size}, 300);
  }
});
Test to see‹/›

Parameter Value

ParameterDescription
valueAn integer representing the number of pixels, or an integer appended with an optional measurement unit (as a string)
function(index, currentHeight)Specify a function that returns the height of the selected element
  • index-Return the index position of the element in the collection

  • currentHeight-Return the current height of the selected element

jQuery HTML/CSS Methods