The width method
The width method allows you to get and change the width of an element.
It is important to remember that we will be getting 'calculated value' width. Unlike the css('width') method, it returns a unitless value (for example 400) and is convenient for mathematical calculations. The method gets the width of the element's content, regardless of the CSS property box-sizing specified. To avoid the inconvenience associated with this, it is recommended to use css('width'). Calculation errors can also occur if the user resizes the page, or if the element or its parent is hidden. The width value does not take into account padding and border values.
Syntax
Get the width of an element. In some cases, the resulting values may be fractional:
$(selector).width();
To change the width of an element, you can simply pass a number (for example, 400), then the units of measurement will be pixels, or a string indicating the units of measurement (for example, '10em'):
$(selector).width(new value);
We can also apply the given function to each element in the set. In this case, the function will receive the number of the element in the set as the first parameter, and the current value of the given width for a specific element as the second parameter. The value of this inside the function will point to the current element. The value of the element's width will change to the one returned by the function:
$(selector).width(function(number in set, current width value))
Example
Let's change the width of div to 40px when clicked, using the width method, and also change its background to green using css:
<div id="test"></div>
#test {
width: 90px;
height: 80px;
background: red;
color: white;
margin-top: 10px;
cursor: pointer;
}
$('#test').one('click', function() {
$(this).width(40).css({
cursor: 'auto',
backgroundColor: 'green'
});
});
See also
-
method
height,
which allows you to get and change the height of an element -
method
innerWidth,
which allows you to get and change the width of an element, taking into account its internal paddings -
method
outerWidth,
which allows you to get and change the width of an element, taking into account its padding and border -
method
css,
which allows you to get and change the CSS styles of an element