JS: Find Element Width

By Xah Lee. Date: . Last updated: .
e.offsetWidth
the visible width of element e. By default, it includes padding, border. But not margin. Does not consider 2D Transform.
e.clientWidth
width, includes padding, but not border nor margin. [see CSS: Margin vs Padding]
e.getBoundingClientRect().width
Return the rendered width of the bounding box. For example, it takes consideration when 2D transform is used to scale the element.

Example

XYZ
<div id="box63800">
XYZ
</div>
#box63800 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: content-box;
}

Here is the JavaScript code

// 2018-08-08
// show several js/dom width values of eleId, show them at anchorId
const displayIt = ((eleId, anchorId) => {
    const xx = document.getElementById (eleId);
    const anchor = document.getElementById (anchorId);
    anchor.innerHTML = `<ul>
<li>offsetWidthis ${xx.offsetWidth}</li>
<li>clientWidthis ${xx.clientWidth}</li>
<li>getBoundingClientRect().width」 is ${xx.getBoundingClientRect().width}</li>
</ul>`;
});

displayIt("box39721", "anchor2_90388");

Example with box-sizing border-box

[see CSS: Box Sizing]

XYZ
<div id="box39721">
XYZ
</div>
#box39721 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: border-box;
}

Example with 2D Transform

[see CSS: 2D Transform]

XYZ
<div id="transf29881">
XYZ
</div>
#transf29881 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: content-box;
transform:rotate(18deg);
}
BUY ΣJS JavaScript in Depth