Thursday, September 4, 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
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS