jQuery Get Width Examples (Div, li, etc.)
If you have read through some of my previous articles, you have seen how we can get the height of a div, li, or any element using jQuery. Now if you are wondering how to get div width or width of any other element, then this article is for you. It is very easy to get div width & can be achieved using just 1 line code. So follow along to find out how you can get div width or width of any other element using jQuery.
How to use jQuery to Get Width of any Element?
jQuery provides us with a very simple function, called width(). So the basic syntax to get width of an element would be as follows:
Basic Syntax to Get element width using jQuery
$(selector).width();
Example 1: Get div width using div ID
$('#my_div').width();Example 2: Get div width using div class
$('.my_div_class').width();Example 3: Get li width
$('ul li').width();Example 4: Get specific li width
$('li#list_item_1').width();
$('#list_item_1').width();Example 5: Get paragraph width
$('p').width();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 width() method on it, what do you expect to happen. Do you think it will add up the widths & widths of all the settings applied? Well, take a guess. If you have guessed that width() ignores all of that, then you are absolutely correct. Using width() only gets the width 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 width and include Padding (Margin & Border are ignored)
$('#my_div').innerWidth();Example 7: Get div width and include Padding & Border (Margin is ignored)
$('#my_div').outerWidth();Example 8: Get div width and include Padding & Border & Margin
$('#my_div').outerWidth(true);So I hope you get the idea. You can apply the methods shown below to elements of your choice to get it’s width. Simple, isn’t it?
Your Turn!
Do you know of any other ways to get width of an element (li, div, etc.) using jQuery? Feel free to suggest by commenting below.