🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

Code has been added to clipboard!

Using jQuery .width() Method to Easily Get the Width of the Element

Reading time 2 min
Published Jan 19, 2018
Updated Oct 1, 2019

jQuery width: Main Tips

  • jQuery .width() returns the width of the first matched element.
  • Provide the new width as the method's parameter to set the width for elements.
  • This tutorial teaches you more about jQuery width and height methods.

Getting and Setting Width

The .width() method allows you to make jQuery get width of the first element matched. The function can also set width for all specified elements.

Remember: the jQuery .width() will not affect padding, margin, or border. They do not belong to the CSS width property.

Click the button in the example to see an alert, showing the current jQuery width of the element. Close the alert to see jQuery set width to the element:

Example
$("button").click(() => {
    alert($("p").width());
});

$("button").click(() => {
    $("p").width(40);
});

To make jQuery get width of the element, use this syntax:

$(selector).width();

The return value will be a number without a unit provided. However, it is always defined in pixels.

Note: you can also get the jQuery window width by including window as the selector.

Alternatively, you can provide a new width to set:

$(selector).width(newWidth);

The newWidth can be defined in:

  • a string (i.e., 400px)
  • a number (i.e., 400)
  • a function returning a value needed

Warning: to get correct results, always make sure the element is not hidden!