jQuery API

.attr()

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 )

    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:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .attr() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Beginner tip:
    Be weary of using .attr() to attach set classes in safari. Use .removeClass or .addClass to assign your class as it won't compile your function.
  • Can we add documentation for the get function specifying the return value if the attribute is not present? (I'm pretty sure the old documentation site said .attr() returns undefined if attributeName is not an attribute of the element, but it should be written here.)
  • The format you suggest is the same format for returning the current value of an attribute. The only way jQuery could do what you ask is to have some static list of boolean attributes that it would check against before returning a value to make sure it shouldn't set the attribute instead. Not only does this add needless overhead, what if you actually want to know whether those boolean attributes are set? What should jQuery do then?

    The best solution: stop being lazy.
  • silver
    HTML5 does not actually have boolean attributes, it allows you to say <input disabled> but it is defined to be precisely equal to <input disabled="">. This can apply to any attribute, not just ones currently defined as boolean. <input value> is just like saying that the default value is blank.
    It's unclear if browsers will support this as written or bend the rules for "certain boolean attributes." But that is moot here.

    Your question used the syntax for "getting an attribute value" but you seemed to imply you wanted it to set the value. That is clearly wrong.

    The syntax for setting an attribute in jquery might look like:
    $(:input).attr('disabled', ''); // sets disabled='' as html5 theoretically specifies
    $(:input).attr('disabled', 'disabled'); // sets disabled='disabled' as required in xhtml
    $(:input).attr('disabled', 'true'); // sets disabled='true', which experimentation shows is currently what jquery returns for '<input disabled>' in html4

    Against html4, <input id=foo disabled> <input id=bar>
    $("#foo").attr('disabled') returns 'true'
    $("#foo").attr('disabled') returns 'false'

    ---
    As for Chris' mention of "a static list of boolean attributes" - it seems to already have such a list, which is what it consults when it fulfills "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."
  • Could you please add a boolean feature for HTML5 attributes, where you don’t need a value.

    E.g. `$(:input).attr ('disabled');`

    I.e. `<input disabled>` instead of `<input disabled="disabled">`