Javatpoint Logo
Javatpoint Logo

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.


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

Parameter Description
Attribute This parameter is used to specify the name of the attribute.
Value This 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()

Let's Work Together!

Javatpoint is passionate to offer better content to the world. Please mail your contribution to We will show your name and create your user profile. You can contribute the following things:
  • Article on Any Topic (which is not available on Javatpoint)
  • Your Interview Experience on Company
  • Company Interview Questions with Answers
  • Recruitment Process of Company
  • Programs, and Algorithm
  • Videos
  • Test Paper
  • Improve Article

Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials