How to use clientWidth() in Javascript

The DOM clientWidth Property is used to return the viewable width of a specific element including padding but excluding the measurement of margin, border, and scrollbar width.

Example: In this example, we are using  clientWidth() .

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Check Width</title>
    <style>
        body{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #GFG {
            height: 30px;
            width: 300px;
            padding: 10px;
            margin: 15px;
            background-color: green;
        }
 
        #checkButton {
            padding: 5px 10px;
            cursor: pointer;
        }
    </style>
</head>
 
<body>
 
    <div id="GFG">
        <b>Division</b>
    </div>
 
    <button id="checkButton" onclick="checkWidth()">
          Check Width
      </button>
 
    <script>
        function checkWidth() {
            const elemWidth = document.getElementById("GFG").clientWidth;
            alert("Width of the div: " + elemWidth + " pixels");
        }
    </script>
 
</body>
 
</html>


Output:

How to find the width of a div using vanilla JavaScript?

To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels.

Below are the different approaches to finding the width of a div using vanilla JavaScript:

Table of Content

  • Using offsetWidth
  • Using clientWidth()
  • Using getComputedStyle()
  • Using getBoundingClientRect()

Similar Reads

Approach 1: Using offsetWidth

The DOM offsetWidth property is used to return the layout width of an element as an integer....

Approach 2: Using  clientWidth()

...

Approach 3: Using getComputedStyle()

The DOM clientWidth Property is used to return the viewable width of a specific element including padding but excluding the measurement of margin, border, and scrollbar width....

Approach 4: Using getBoundingClientRect()

...