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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#myElement{
border:1px solid green;
display: inline-block;
}
</style>
</head>
<body>
<h2>Get Width of HTML Element using JavaScript</h2>
<div id="myElement">
<p>Div Part 1.</p>
<p>Div Part 2.</p>
</div>
<br><br>
<button type="button" onclick="execute()">Click Me</button>
<script>
function execute(){
var element = document.getElementById('myElement');
var width = element.clientWidth;
console.log("Width is " + width + "px");
}
</script>
</body>
</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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
#myElement{
border:1px solid green;
display: inline-block;
padding: 5px;
}
</style>
</head>
<body>
<h2>Get Width of HTML Element using JavaScript</h2>
<div id="myElement">
<p>Div Part 1.</p>
<p>Div Part 2.</p>
</div>
<br><br>
<button type="button" onclick="execute()">Click Me</button>
<script>
function execute(){
var element = document.getElementById('myElement');
var width = element.clientWidth;
console.log("Width is " + width + "px");
}
</script>
</body>
</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.