attr() method in jQuery

attr() in jQuery

This method is used to Get or Set the value of an attribute of the first element in the set of matched elements.

Using a looping construct such as jQuery's each() or map() method, each elements values can be get individually.

Syntax 1 - Get the value of an attribute for the element specified.

$(selector).attr(attributeName)

  • attributeName - The name of the attribute.
Syntax 2 - Set value for attribute in the set of matched elements.

$(selector).attr(attributeName,attributeValue)

  • attributeName - The name of the attribute.
  • attributeValue - A value to be set for the attribute. If null, the specified attribute will be removed.
Syntax 3 - Set more than one attributes for the set of matched elements.

$(selector).attr({attributeName1:value1,...,attributeNamen:valuen)

  • attributeName - The name of the attributes.
  • value - A value to set for the attributes. If null, the specified attribute will be removed.
Syntax 4

$(selector).attr(attributeName,function(index,currentAttributeValue))

  • attributeName - The name of the attribute.
  • index - Index position of the element in the set.
  • currentAttributeValue - The old attribute value as arguments.

Example 1 - Get attribute value

Try Yourself

Example 2 - set/create attribute value

Try Yourself

Example 3 - set/create many attribute values

Try Yourself

Example 4 - Get old value and set new value

Try Yourself

Example 5 - Difference between attr() and prop()

Try Yourself