.attr()

.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 )

    attributeNameThe name of the attribute to get.

It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() 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: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

Example:

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

<!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>

Demo:

.attr( attributeName, value ) Returns: jQuery

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

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

    attributeNameThe name of the attribute to set.

    valueA value to set for the attribute.

  • version added: 1.0.attr( map )

    mapA map of attribute-value pairs to set.

  • version added: 1.1.attr( attributeName, function(index, attr) )

    attributeNameThe name of the attribute to set.

    function(index, attr)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 and powerful way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Let's consider the following image:

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

Setting a simple attribute

We can change the alt attribute by simply passing the name of the attribute and its new value to the .attr() method:

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

We can add an attribute the same way:

$('#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, we can pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:

$('#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!

Computed attribute values

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

$('#greatphoto').attr('title', function() {
  return this.alt + ' - photo by Kelly Clark'
});

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

Examples:

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

<!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: "/images/hat.gif",
          title: "jQuery",
          alt: "jQuery Logo"
        });
    $("div").text($("img").attr("alt"));</script>
</body>
</html>

Demo:

Example: Disables buttons greater than the 1st button.

<!DOCTYPE html>
<html>
<head>
  <style>button { margin:10px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<button>0th Button</button>
  <button>1st Button</button>
  <button>2nd Button</button>
<script>$("button:gt(1)").attr("disabled","disabled");</script>
</body>
</html>

Demo:

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

<!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>

Demo:

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

<!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 "/images/" + this.title; 
        });
</script>
</body>
</html>

Demo: