Friday, June 12, 2026
HomeLanguagesJavascriptHow to find the width of a div using vanilla JavaScript?

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.

Syntax:

element.offsetWidth
    Return Value:

  • Returns the corresponding element’s layout pixel width.

Example:

The following program will illustrate the solution using offsetWidth:
Program 1:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        neveropen
    </title>
  
    <style>
        #GFG {
            height: 30px;
            width: 300px;
            padding: 10px;
            margin: 15px;
            background-color: green;
        }
    </style>
</head>
  
<body>
  
    <div id="GFG">
        <b>Division</b>
    </div>
  
    <button type="button"
            onclick="Geeks()">
        Check
    </button>
  
    <script>
        function Geeks() {
  
            var elemWidth = 
                document.getElementById("GFG").offsetWidth;
            alert(elemWidth);
        }
    </script>
</body>
  
</html>


Output:

320

The another method to measure the width of a div element we will utilize the clientWidth() property of JavaScript.

The following program will illustrate the solution using clientWidth:
Program 2:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        neveropen
    </title>
  
    <style>
        #GFG {
            height: 30px;
            width: 300px;
            padding: 10px;
            margin: 15px;
            background-color: green;
        }
    </style>
</head>
  
<body>
  
    <div id="GFG">
        <b>Division</b>
    </div>
  
    <button type="button" onclick="Geeks()">
        Check
    </button>
  
    <script>
        function Geeks() {
  
            var elemWidth = 
                document.getElementById("GFG").clientWidth;
            alert(elemWidth);
        }
    </script>
</body>
  
</html>


Output:

320

Note: clientWidth returns the inner width which includes padding but excludes borders and scroll bars whereas offsetWidth returns the outer width which includes padding and borders.

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS