Open In App

jQuery width() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The width() is an inbuilt function in JavaScript which is used to check the width of an element. It does not check the padding, border, and margin of the element.

Syntax:

$("param").width()

Parameters: Here parameter is “param” which is the class or id of the element whose width is to be extracted.

Return values: It returns the width of the selected element.

jQuery code to show the working of this function:

Example 1:

html




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                let msg = "";
                msg += "Width of div: " + $("#demo").width();
                $("#demo").html(msg);
            });
        });
    </script>
    <style>
        #demo {
            height: 150px;
            width: 350px;
            padding: 10px;
            margin: 3px;
            border: 1px solid blue;
            background-color: lightgreen;
        }
    </style>
</head>
 
<body>
    <div id="demo"></div>
    <button>Click Me!!!</button>
    <p>Click on the button and check
        the width of the element
        (excluding padding).
    </p>
</body>
 
</html>


Output:

jquery-44

jQuery also includes innerWidth() method i.e, it is also used to check the inner width of the element including padding.

Syntax:

$("param").innerWidth()

Parameters: Here parameter “param” is the class or id of the element whose width to be extracted.

Return value: It returns the width of the selected element.

Example 2:

html




<!DOCTYPE html>
<html>
 
<head>
                jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                let msg = "";
                msg += "Inner width of div: " + $("#demo")
                    .innerWidth() + "</br>";
                $("#demo").html(msg);
            });
        });
    </script>
</head>
<style>
    #demo {
        height: 150px;
        width: 350px;
        padding: 10px;
        margin: 3px;
        border: 1px solid blue;
        background-color: lightgreen;
    }
</style>
 
<body>
    <div id="demo"></div>
    <button>Click Me!!!</button>
    <p>Click on the button and check
        the innerWidth of an element
        (includes padding).
    </p>
</body>
 
</html>


Output:

jquery-45



Last Updated : 10 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads