jQuery width() Method

The jQuery width() method can be used to get or set the width of the selected element. It is also useful when you want to find the width of the elements.

You can overwrite the width of the selected with the method. It will not include the padding, border, and margin of the selected element.

jQuery width() Method

Syntax

The syntax of this method is given below:-

Return the width of an element
$(selector).width()
Sets the width of an element
$(selector).width(value)
Use Function to Set the width of an element
$(selector).width(function(index, current_width))

Description of the Parameters

The description of the parameters are given below.

Parameter Name Description
selector Specify the selector for selecting the elements and return or sets the width. You have to use tag name, class name, or id of the elements to select.
value It is the value of the width of an element you want to set for the selected element. The value is in px, em, etc.
index It returns the index position of the selected element.
current_width It returns the current width of the selected element.

jQuery width() Method to Get or Return the Value of Width

To get the width of the selected element, you have to use this method. If the element contains some width, it returns the width of the selected element to display. However, the width does not contain the padding, margin, and border of the selected element.

Example

Test it Live

Output

When you click the button given above, it returns the width and displays in the alert box. The width is showing in the alert box as it is present in the selected element.

Set the Width of an Element Using the Method

You can also set the width of the selected element using the method. Specify the width as the parameter of the method whose value is in px, em, etc. The below example contains the div element with some width value. When you set the value, the method replaces the old value with the newly specified value.

Test it Live

Output

You have to click the button given above to set the width of the selected element. It overwrites the old width with the new width you have specified in the example above.

You may also like to read

I hope you like this tutorial on jQuery width() method. If you have any queries regarding the tutorial, please comment below.

References