Get width and height of an HTML element with jQuery
This post will discuss how to get the width and height of an HTML element with jQuery.
There are several alternatives to get the width and height of an element with JavaScript. This post provides an overview of some of the available alternatives in jQuery.
1. Using width() and height() method
jQuery offers the .width() and the .height() method, which returns the actual width and height of an element’s content, respectively.
For example, the following code returns ‘500 × 100’ value, which is the actual space the displayed content takes up.
JS
|
1 2 3 4 5 |
$(document).ready(function() { var width = $("#container").width(); var height = $("#container").height(); alert(`${width} x ${height}`); }); |
HTML
|
1 |
<div id="container" class="main-class"></div> |
CSS
|
1 2 3 4 5 6 |
.main-class { border: 1px solid gray; width: 500px; height: 100px; padding: 10px; } |
2. Using css() method
Note that both .width() and .height() returns a unit-less value. If you need values with units intact like ‘500px’, use .css() method instead. Here’s a working example, which returns actual width and height of an element in pixels:
JS
|
1 2 3 4 5 |
$(document).ready(function() { var width = $("#container").css("width"); var height = $("#container").css("height"); alert(`${width} x ${height}`); }); |
HTML
|
1 |
<div id="container" class="main-class"></div> |
CSS
|
1 2 3 4 5 6 |
.main-class { border: 1px solid gray; width: 500px; height: 100px; padding: 10px; } |
3. Using .outerWidth() and .outerHeight() method
If you need to include padding and border information, and optionally the margin, consider using the .outerWidth() and .outerHeight() method.
JS
|
1 2 3 4 5 |
$(document).ready(function() { var outerWidth = $("#container").outerWidth(); var outerHeight = $("#container").outerHeight(); alert(`${outerWidth} x ${outerHeight}`); }); |
HTML
|
1 |
<div id="container" class="main-class"></div> |
CSS
|
1 2 3 4 5 6 |
.main-class { border: 1px solid gray; width: 500px; height: 100px; padding: 10px; } |
That’s all about getting the width and height of an HTML element with jQuery.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)