jquery
  1. jquery-width

jQuery width()

The width() method in jQuery is used to get or set the width of the matched elements. It is a useful and popular method that can be used to manipulate the size of elements on a webpage.

Syntax

To get the width of an element, use the following syntax:

$(selector).width();

To set the width of an element, use the following syntax:

$(selector).width(value);

Use

The width() method is commonly used to manipulate the size of elements on a webpage, such as images, divs, or containers. It can be used to set the width of an element to a specific value, or to get the width of an element for use in other calculations or manipulations.

Example

Here is an example of using width() to set the width of an image element:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery width() Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("img").width(300);
            });
        });
    </script>
    <style>
        img {
            width: 200px;
            height: auto;
        }
    </style>
</head>
<body>
    <img src="https://static.additionalsheet.com/images//others/alisa.jpg">
    <br><br>
    <button>Set Width</button>
</body>
</html>
Try Playground

In this example, we use the width() method to set the width of an image to 500 pixels when the button is clicked. The original width of the image is 300 pixels, which is defined in the CSS.

Summary

The width() method in jQuery is a useful tool for manipulating the size of elements on a webpage. It can be used to get or set the width of an element, and can be applied to a wide range of elements, including images, divs, and containers. Use it to make your webpages more responsive and dynamic.

Published on: