The innerWidth method
The innerWidth
method allows you to get and change the width of an element taking into account its internal padding. It is important to remember that we will get 'calculated value' width (eng. computed width). Errors in calculation can also occur if the user changes the page dimensions, or if the element or its parent is hidden. The width value does not take into account the thickness of the element's border.
Syntax
Get the width of an element. In some cases, the resulting values may be fractional:
$(selector).innerWidth();
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).innerWidth(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).innerWidth(function(number in set, current width value));
Example
For comparison, let's display information about the width of the paragraph #test
, obtained by the methods width
and innerWidth
:
<p id="test">text</p>
<p id="out1"></p>
<p id="out2"></p>
p {
margin: 10px;
padding: 5px;
border: 2px solid blue;
}
let w1 = $('#test').width();
let w2 = $('#test').innerWidth();
$('#out1').text(w1);
$('#out2').text(w2);
We'll see a difference of 10px
, which is the sum of our left and right paddings.
See also
-
method
width
,
which allows you to get and change the width of an element -
method
outerWidth
,
which allows you to get and change the width of an element, taking into account its padding and border