HTML DOM clientWidth Property


The HTML DOM clientWidth property is used to get the viewable width of an HTML element. This width includes padding but excludes any border, scrollbar and margins. It will only return the element width even if the content overflows from the element.

Syntax

Following is the syntax for clientWidth property −

element.clientWidth

Example

Let us see an example for the HTML DOM clientWidth property −

<!DOCTYPE html>
<html>
<head>
<style>
#divStyle {
   width: 200px;
   height: 200px;
   padding: 10px;
   margin: 15px;
   border: 5px solid blue;
   background-color: lightgreen;
}
</style>
</head>
<body>
<p>Click the below button to get the widhth of the div</p>
<button onclick="getWidth()">GET WIDTH</button>
<div id="divStyle">
<b>A sample div</b>
</div>
<p id="Sample"></p>
<script>
   function getWidth() {
      var x = document.getElementById("divStyle");
      var txt = "Width including padding: " + x.clientWidth + "px";
      document.getElementById("Sample").innerHTML = txt;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking GET WIDTH −

In the above example −

We have created a div with id “styleDIV” and have a style applied to it using its id.

#divStyle {
   width: 200px;
   height: 200px;
   padding: 10px;
   margin: 15px;
   border: 5px solid blue;
   background-color: lightgreen;
}

The div −

<div id="divStyle">
<b>A sample div</b>
</div>

We have then created a button GET WIDTH that will execute the getWidth() method on click −

<button onclick="getWidth()">GET WIDTH</button>

The getWidth() gets the <div> element using the getElementById() method and assigns it to variable x. Then using the clientWidth property on the <div> we get its width and after appending some text assigns it to variable txt. The text inside txt is then displayed inside the paragraph using the innerHTML property on the paragraph and assigning the txt variable to it −

function getWidth() {
   var x = document.getElementById("divStyle");
   var txt = "Width including padding: " + x.clientWidth + "px";
   document.getElementById("Sample").innerHTML = txt;
}

Updated on: 07-Aug-2019

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements