jQuery width() Method

jQuery | width() Method: Learn about the jQuery width() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

width() Method

It is very important to know the dimensions of the element that has been placed on the web page. It includes – height, width, innerHeight, innerWidth, etc. For example, the container created, and the images used should have a proper dimension ratio to make the web page look more professional. That's why we need to know the dimensions over here. So, over here, we'll discuss the width() method in detail.

The width() method helps to set or get the width of the selected element. The element whose dimensions have to be known is passed here as a selector, and this method gives the numerical value of the width. The width() method does not return the width including the padding and margin.

width() Method Syntax


In order to set the width of the element, the value of the width has to be given. This will help to set the width of all the matched elements. If no value is given, then the method will return the width of the first element matched. This way the width() method works in jQuery.

The below example shows the implementation of this method. When the button provided is clicked, it helps to return the width of the image.

jQuery width() Method Example

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <h2>jQuery - Width</h2>
    <p>Click the button to get the width of the image.</p>
    <img style="height: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
  <script type="text/javascript">
            var width = $('img').width();
            $('h3').html('Width of the Image is: ' + width);


Example 1: jQuery width() Method

All jQuery Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.