jQuery width() Method

Last Updated:

jQuery width() Method

The jQuery width() method gets or sets the width of the selected elements.

Get Width

In the following example, we will get the width of the div container.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 2px solid black; height: 100px; width: 100px; } </style> </head> <body> <h1>jQuery width() Method</h1> <div></div> <p>Click on the button to find the width of div.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ alert($("div").width()); }); }); </script> </body> </html>

Syntax

// To get width $(selector).width(); //To set width $(selector).width(integer) //To callback $(selector).width(function(index, width));

Parameter Values

ValueTypeExplanation
integer Optional Specifies the width in px.
function(index, width) Optional Specifies a function that returns the new width of selected elements
Parameters Explanation
  • index - Returns the index position of the element in the set
  • width - Returns the current width of the selected element

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
width()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Width

In the following example, we will set the width of the div container to 200px.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 2px solid black; height: 100px; width: 100px; } </style> </head> <body> <h1>jQuery width() Method</h1> <div></div> <p>Click on the button to set div's width to 200px.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ $("div").width(200); }); }); </script> </body> </html>

Set Width with Callback

In the following example, we will set the width of the two div containers using a callback.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 1px solid black; width: 100px; height: 50px; margin: 10px; } </style> </head> <body> <h1>jQuery width() Method</h1> <div>Child 1</div> <div>Child 2</div> <p>Click on the button to change the first div's width to 100px and second div's width to 150px.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ $("div").width(function(index, myWidth){ $("div").eq(index).width(myWidth * (index + 2)); }); }); }); </script> </body> </html>

Share this Page

Meet the Author