Saturday, December 13, 2025
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
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS