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>
        zambiatek
    </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>
        zambiatek
    </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

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button