The width() method in JQuery is used to get and set the width of an HTML element.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p style = "background-color:violet; height:100px; width:150px"> Hello World </p> <button> Click it </button> <script> $('button').click( function() { alert("The width of the p element is : "+$('p').width()); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p style = "background-color:violet; height:100px; width:150px"> Hello World </p>
And we have a <button> element,
<button> Click it </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { alert("The width of the p element is : "+$('p').width()); });
And an alert is generated,
alert("The width of the p element is : "+$('p').width());
Now, if we see the output (i.e. The alert),
You get the width of the <p> element (i.e. 150).
This is because the width() method is used to get the width of the <p> element.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p style = "background-color:violet; height:100px;"> Hello World </p> <button> Click it </button> <script> $('button').click(function(){ $('p').width("150px"); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p style = "background-color:violet; height:100px;"> Hello World </p>
And we have a <button> element,
<button> Click it </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { $('p').width("150px"); });
And the width() method is used to set the width of the <p> element to 150px.
$('p').width("150px");
Now, if we see the output, the width of the <p> element got set to 150px.