JavaScript – Get Width of an HTML Element in Pixels
To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth
property of this HTML Element.
clientWidth
property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element. Border, margin and scrollbar(if any) are not considered for clientWidth
computation.
In the following example, we will get the width of the HTML Element, which is selected by id "myElement"
.
example.html
Try this html file online, and click on the Click Me
button. Width of the HTML Element #myElement
will be printed to console, as shown in the following screenshot.
Let us now provide some padding to the HTML Element #myElement
, and get the width using clientWidth
property.
example.html
In the first example, without padding, the width of the HTML Element is 70px. Now with a padding of 5px, meaning padding on all sides is 5px, the new width of the HTML element is 70px + padding-left + padding-right. Since padding on left and right are 5px each, the resulting width is 70px + 5px + 5px = 80px.
Conclusion
In this JavaScript Tutorial, we learned how to get the width of an HTML Element in pixels, using JavaScript.