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:

$(selector).attr({attribute:value, attribute:value,...})

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.

<!DOCTYPE html>
<script src=""></script>
        $("img").attr("width", "500");
<img src="good-morning.jpg" alt="Good Morning Friends"width="284" height="213"><br>
<button>Set the width attribute of the image</button>

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.
Related Tutorial
Follow Us #
Contents +