Description
The .attr() method sets or returns attribute values of selected elements.
Note: As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr()
should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop()
method.
Return Attribute Value
Return the value of an attribute for the selected element.
This method has the form:
.attr(attribute)
Parameter | Description |
---|---|
attribute | Specifies the attribute to get the value of |
Return Value
This form returns a String object.
Set Attribute/Value
Set the attribute and value of the selected elements.
This method has the alternate form:
.attr(attribute,value)
Parameter | Description |
---|---|
attribute | Specifies the name of the attribute |
value | Specifies the value of the attribute |
Return Value
This form returns a jQuery object.
Set Attribute/Value Using a Function
Using a function to set the attribute value for the selected elements.
This method has the alternate form:
.attr(attribute,function(index,oldvalue))
Parameter | Description |
---|---|
attribute | Specifies the name of the attribute |
function(index, oldvalue) | Specifies a function that returns the attribute value to set.
|
Return Value
This form returns a jQuery object.
Set Multiple Attribute/Value Pairs
Set one or more attributes and values for the selected elements.
This method has the alternate form:
.attr({ attribute:value,attribute:value, ...})
Parameter | Description |
---|---|
{attribute:value, attribute:value, ...} | Specifies one or more attribute/value pairs |
Return Value
This form returns a jQuery object.
Examples
Set the width attribute of an image:
$("button").click(function(){
$("img").attr("width","150");
});