.attr()

jQuery

.attr()


Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

Contents:

.attr( attributeName )Returns: String

Description: Get the value of an attribute for the first element in the set of matched elements.

  • version added: 1.0.attr( attributeName )

    • attributeName
      Type: String
      The name of the attribute to get.

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:

  1. Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
  2. Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

Example:

Find the title attribute of the first <em> in the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<style>
em { color:blue; font-weight:bold; }
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>
Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>
The title of the emphasis is:<div></div>
<script>
var title = $("em").attr("title");
$("div").text(title);
</script>
</body>
</html>

.attr( attributeName, value )Returns: jQuery

Description: Set one or more attributes for the set of matched elements.

  • version added: 1.0.attr( attributeName, value )

    • attributeName
      Type: String
      The name of the attribute to set.
    • value
      Type: String or Number
      A value to set for the attribute.
  • version added: 1.0.attr( attributes )

    • attributes
      An object of attribute-value pairs to set.
  • version added: 1.1.attr( attributeName, function(index, attr) )

    • attributeName
      Type: String
      The name of the attribute to set.
    • function(index, attr)
      Type: Function()
      A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

1
<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute

To change the alt attribute, simply pass the name of the attribute and its new value to the .attr() method:

1
$('#greatphoto').attr('alt', 'Beijing Brush Seller');

Add an attribute the same way:

1
2
$('#greatphoto')
.attr('title', 'Photo by Kelly Clark');

Setting several attributes at once

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a plain JavaScript object. Each key-value pair in the object adds or modifies an attribute:

1
2
3
4
$('#greatphoto').attr({
alt: 'Beijing Brush Seller',
title: 'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

Note: jQuery prohibits changing the type attribute on an <input> or <button> element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

Computed attribute values

By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

1
2
3
$('#greatphoto').attr('title', function(i, val) {
return val + ' - photo by Kelly Clark'
});

This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Examples:

Example: Set some attributes for all <img>s in the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<style>
img { padding:10px; }
div { color:red; font-size:24px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<img />
<img />
<img />
<div><B>Attribute of Ajax</B></div>
<script>
$("img").attr({
src: "/resources/hat.gif",
title: "jQuery",
alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
</script>
</body>
</html>

Example: Set the id for divs based on the position in the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
span { color:red; }
b { font-weight:bolder; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
<script>
$("div").attr("id", function (arr) {
return "div-id" + arr;
})
.each(function () {
$("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
</script>
</body>
</html>

Example: Set the src attribute from title attribute on the image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<img title="hat.gif"/>
<script>
$("img").attr("src", function() {
return "/resources/" + this.title;
});
</script>
</body>
</html>