The attr() method is used to get and set the attribute 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> Enter the value : <input type = "text"/> <br/><br/> <button> Click it </button> <script> $('button').click( function() { alert("The input element is of type : " + $("input").attr("type")); }); </script> </body> </html>
So, if we look at the above code, we have an <input> element that has an attribute i.e. "type = 'text'".
<input type = "text"/>
And we have a <button> element,
<button> Click it </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { alert("The input element is of type : " + $("input").attr("type")); });
And an alert is generated,
alert("The input element is of type : " + $("input").attr("type"));
Now, if we see the output (i.e. The alert),
You get the type of the <input> element(i.e. text).
This is because the attr("type") method is used to get the attribute i.e. type of the <input> 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> <button> Click to increase the height of the below image </button> <br/><br/> <img src="airplane.jpg" alt="Airplane" width="150" height="103"> <script> $('button').click( function() { $('img').attr("height", "200"); }); </script> </body> </html>
So, if we look at the above code, we have a <button> element,
<button> Click to increase the height of the below image </button>
And we have an <input> element that has an attribute i.e. "type = 'text'".
<input type = "text"/>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { $('img').attr("height", "200"); });
And locates the <img> element and increases the height of the <img> element to 200.
$('img').attr("height", "200");
This is because the attr("height", "200") method is used to set/change the attribute i.e. height of the <input> element.
Now, what if you want to change, both height and width of the <img> element?
Let us see in the below example.
<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> <button> Click to increase the height and width of the below image </button> <br/><br/> <img src="airplane.jpg" alt="Airplane" width="150" height="103"> <script> $('button').click( function() { $('img').attr({height: "200", width: "300"}); }); </script> </body> </html>
So, we have modified the above example to modify the height and width.
And all we have done is, modified the attr() method of the JQuery element.
$('img').attr({height: "200", width: "300"});
So, inside the attr() method, we have used the new values of height and width enclosed within braces (i.e. {}).