• jQuery Video Tutorials

jQuery innerWidth() Method



The innerWidth() method in jQuery is used to get the inner width of the first matched element in the set of matched elements, including the padding but not including borders or margins.

This method returns the inner width of the first matched element in pixels as an integer value. If there are no matched elements, it returns undefined.

Syntax

Following is the syntax of the innerWidth() element in jQuery −

$(selector).innerWidth()

Parameters

This method does not accept any parameters.

Example 1

In this example, we are using the innerWidth() method to return the inner width of the selected element (in this case, it is <div> element) −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const innerWidth = $("#element").innerWidth();
                alert("Inner width of the element: " + innerWidth);
            });
        });
    </script>
</head>
<body>
    <div id="element" style="width: 200px; padding: 20px; border: 2px solid black; background-color: yellow;">
        This is a div element.
    </div>
    <button>Get Inner Width</button>
</body>
</html>

When we click on the button, it will trigger an alert displaying the inner width of the <div> element.

Example 2

In this example, we have multiple <div> elements in the matched elements set. So, when the innerWidth() method is triggered, it returns the inner width of the first matched element −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                const innerWidth = $("#element").innerWidth();
                alert("Inner width of the first selected element: " + innerWidth);
            });
        });
    </script>
</head>
<body>
    <div id="element" style="width: 200px; padding: 20px; border: 2px solid black; background-color: yellow;">
        div element (width: 200px padding: 20px)
    </div>
    <div id="element" style="width: 250px; padding: 25px; border: 2px solid black; background-color: yellow;">
        div element (width: 250px padding: 25px)
    </div>
    <div id="element" style="width: 300px; padding: 30px; border: 2px solid black; background-color: yellow;">
        div element (width: 300px padding: 30px)
    </div>
    <button>Get Inner Width of first selected element.</button>
</body>
</html>

When we click the button, it gives the inner width of the first selected <div> element in the matched set.

jquery_ref_html.htm
Advertisements