jQuery Get Height Examples (Div height, li height, etc.)
While working with jQuery, at some point of time or the other, you may have come across a requirement that requires you to get div height or get li height or get height of any other element. If you are wondering how complicated that would be, you would be pleased to hear that it’s not at all hard to do so. In fact, it’s very easy & can be achieved using just 1 line code. So follow along to find out how you can get div height or height of any other element using jQuery.
How to Get Height using jQuery
jQuery provides us with a very simple function, called height(). So the basic syntax to get the height of an element would be as follows:
Basic Syntax of jQuery to Get element height
$(selector).height();
Example 1: Get div height using div ID
$('#my_div').height();Example 2: Get div height using div class
$('.my_div_class').height();Example 3: Get li height
$('ul li').height();Example 4: Get the height of a specific list item (li) using the list item ID
$('li#list_item_1').height();
$('#list_item_1').height();Example 5: Get paragraph height
$('p').height();One thing to note. If you have, let’s say, a div. You have applied a border, margin and padding to this div. If you now use height() method on it, what do you expect to happen. Do you think it will add up the widths & heights of all the settings applied? Well, take a guess. If you have guessed that height() ignores all of that, then you are absolutely correct. Using height() only gets the height of the actual content in the div, li, etc. It does not consider the padding, margin, etc. applied on the element. So if you want to add the padding, margins, borders, use the codes below.
Example 6: Get div height and include Padding (Margin & Border are ignored)
$('#my_div').innerHeight();Example 7: Get div height and include Padding & Border (Margin is ignored)
$('#my_div').outerHeight();Example 8: Get div height and include Padding & Border & Margin
$('#my_div').outerHeight(true);So I hope you get the idea. You can apply the methods shown below to elements of your choice to get it’s height. Simple, isn’t it?
Your Turn!
Do you know of any other ways to get height of an element (li, div, etc.) using jQuery? Feel free to suggest by commenting below.