Example

Set the width attribute of an image:

$("button").click(function(){
  $("img").attr("width","150");
});

Try it yourself »

Definition and Usage

The attr() method sets or returns attribute values of selected elements.

This method works differently depending on the parameters.


Return Attribute Value

Return the value of an attribute for the selected element.

Syntax

$(selector).attr(attribute)
Try it yourself »

Parameter Description
attribute Specifies the attribute to get the value of


Set Attribute/Value

Set the attribute and value of the selected elements.

Syntax

$(selector).attr(attribute,value)
Try it yourself »

Parameter Description
attribute Specifies the name of the attribute
value Specifies the value of the attribute


Set Attribute/Value Using a Function

Using a function to set the attribute value for the selected elements.

Syntax

$(selector).attr(attribute,function(index,oldvalue))
Try it yourself »

Parameter Description
attribute Specifies the name of the attribute
function(index,oldvalue) Specifies a function that returns the attribute value to set.
  • index - Optional. Receives the index position of the selector
  • oldvalue - Optional. Receives the current attribute value of the selector


Set Multiple Attribute/Value Pairs

Set one or more attributes and values for the selected elements.

Syntax

$(selector).attr({attribute:value, attribute:value, ...})
Try it yourself »

Parameter Description
{attribute:value, attribute:value, ...} Specifies one or more attribute/value pairs