Introduction:

In this article we will explain how to get or set width of selected html element in jQuery with example.

Description:

jQuery width() method is used to get or set the width of matched element.

To get width: When this method is used to get the width, it get the width of first matched element.

To set width:When this method is used to set the width, it sets the width for every matched element.

Note: If we pass parameter, it sets the width of the element otherwise it simply get the width of the element.

Example of jQuery width() method

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Jquery Tutorials</title>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
    <script>
        $(document).ready(function () {
            $(".div").css("background", "#c0c0c0").width("200px");
            $("#span1").text($(".div").width());
        });
    </script>
    <div class="div" style="height:100px;">DIV</div>
  <span> Div Width:</span> <span id="span1"></span>
</body>
</html>

Output:

Get and set width of element in jQuery

In  Above code snippet will first change the background color and set the width of the “div” tag to 200px.

And it also will show the width of “div” element in span tag.

I hope it will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like