jQuery attr()

The jQuery attr() method is used to set or return attributes and values of the selected elements.

There are two usage of jQuery attr() method.

  1. To return attribute value: This method returns the value of the first matched element.
  2. To set attribute value: This method is used to set one or more attribute/value pairs of the set of matched elements.

Syntax:

To return an attribute's value:

To set an attribute and value:

To set an attribute and value by using a function:

To set multiple attributes and values:

Parameters of jQuery attr() method

ParameterDescription
AttributeThis parameter is used to specify the name of the attribute.
ValueThis parameter is used to specify the value of the attribute.
Function (index, currentvalue)It is a parameter to specify a function that returns an attribute value to set.
  • Index: It is used to receive the index position of the element in the set.
  • Currentvalue: It is used to provide the current attribute value of selected elements.

Example of jQuery attr() method

Let's take an example to demonstrate jQuery attr() method.

Test it Now

Benefits of using jQuery attr() method

It provides two main benefits:

  • Convenience: When you use jQuery attr() method to get the value of the attribute of an element then it can be call directly on a jQuery object and chained to other jQuery methods.
  • Cross-browser consistency: You can get rid from inconsistently changing of attribute's value on different browsers or even on different versions of a single browser.
Next TopicjQuery prop()