jQuery attr()

The jQuery attr() method sets or returns the value of a property of selected elements.

Syntax:

When used to return an attribute’s value:

$(selector).attr(attribute)   

When used to set an attribute and value:

$(selector).attr(attribute,value)  

When used to set an attribute and value by using a function:

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

When used to set multiple attributes and values:

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

Attribute:

  • Attribute is a compulsory parameter of jQuery attr() method, as it specifies the name of the attribute.

Value:

  • Value is a compulsory parameter of jQuery attr() method, as it specifies the value of the attribute.

Function:

  • It is an optional parameter.
  • The function parameter is used to return the attribute value.

Index:

  • Index is an argument passed within the function.
  • It is used to give an index position to an element in the set.

Currentvalue:

  • This parameter is used to provide the current attribute value.

 

Example 1

<!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="img_girl.jpg" width="200" height="300">
 
<button>Click me</button>  
</body>  
</html>

Try it

JS Bin on jsbin.com

Please Share