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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        GeeksforGeeks
    </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>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        GeeksforGeeks
    </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>

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.