The jQuery attr() method is used to set or return attributes and values of the selected elements.
There are two usage of jQuery attr() method.
Syntax:
To return an attribute's value:
$(selector).attr(attribute)
To set an attribute and value:
$(selector).attr(attribute,value)
To set an attribute and value by using a function:
$(selector).attr(attribute,function(index,currentvalue))
To set multiple attributes and values:
$(selector).attr({attribute:value, attribute:value,...})| Parameter | Description |
|---|---|
| Attribute | This parameter is used to specify the name of the attribute. |
| Value | This parameter is used to specify the value of the attribute. |
| Function (index, currentvalue) | It is a parameter to specify a function that returns an attribute value to set.
|
Let's take an example to demonstrate jQuery attr() method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width", "500");
});
});
</script>
</head>
<body>
<img src="good-morning.jpg" alt="Good Morning Friends"width="284" height="213"><br>
<button>Set the width attribute of the image</button>
</body>
</html>It provides two main benefits:
