Home >>jQuery Tutorial >jQuery attr() Method

jQuery attr() Method

jQuery attr() Method

jQuery attr() methodin jQuery is used to returns attributes and values (it returns the value of the FIRST matched element) of the selected elements.

This method sets one or more attribute/value pairs for the set of matched elements.

Syntax:

Return the value of an attribute:

$(selector).attr(attribute)

Set the attribute and value:

$(selector).attr(attribute,value)

Set attribute and value using a function:

$(selector).attr(attribute,function(index,currentvalue))

Set multiple attributes and values:

$(selector).attr({attribute:value, attribute:value,...})

Parameter Values

Parameter Description
attribute It is used to Specifies the name of the attribute
value It is used to Specifies the value of the attribute
function(index,currentvalue) It is used to Specifies a function which returns the attribute value
  • index – used to receives the index position of the element in the set
  • currentvalue – used to receives the current selected elements of attribute value
Here is an Example of jQuery attr() Method:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn1").click(function(){
$(".atrimg").attr("width", "350");
});
});
</script>
</head>
<body>
<img src="C:\Users\GautamArya\Desktop\jq/1.jpg" class="atrimg" alt="Pulpit Rock" width="250" height="250"><br>
<button class="btn1">click me</button>
</body>
</html>

Output:
Pulpit Rock