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() or .map() 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.

If we try to get the value of an attribute that has not been set, the .attr() method returns undefined.

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.min.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.min.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.min.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.min.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.min.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.
  • Jpmt Rama
    Great job done by you, thanks alot
  • kevin
    Does this work with the new html5 data-* attributes? Or do I need to do something like this http://binarykitten.me.uk/dev/jq-plugins/288-html5-data-attributes-and-jquerys-data-pairing-made-in-heaven.html
  • Eric Thibault
    when I change the href of a text link, Internet Explorer also changes the text attribute! in FireFox all is good! When I change the href of an image, both browsers performs ok.
    Any hint?
  • You cannot use attr() with <button value=""> with IE6 or IE7

    http://stackoverflow.com/questions/487056/retrieve-button-value-with-jquery</button>
  • Bruno
    $("a").attr("onclick") doesn't return the string the attribute contains. How could I fix it?
  • Paul Moment
    FYI, in case anyone runs into it: Doing a test for the 'maxlength' attr on a form field like $("#field").attr("maxlength") doesn't actually return "undefined" in IE or Safari (seemed to be fine in FF). Instead, what I got was a really long integer that looked like a browser-standard maxlength. The integer was different in IE and Safari, but pretty long. So, I had to do some class checking instead to do a workaround. Checking something like $("#field").attr("cheese") actually returned an "undefined" as expected.
  • Charles B
    How do you set the a href attribute?
  • JC
    Put all the url string in an array .. give the corresponding array index as the value for the href using attr method

    this is the way of setting the href attr

    $("a").attr("href",array[index]);
  • JC
    $("a").attr("href","http://www.google.com");
  • JC
    not able to apply the id value dynamically using attr() method
    $("span").each(function(index) {
    $(this).attr("id",index);
    });

    not working as expected .. the id is not applied at all for the spans, any ideas guys ?

  • it's probably not working because IDs aren't allowed to begin with a number, let alone be a number in their entirety. See if this works:

    $('span').attr('id', function(index) {
    return 'span-' + index;
    });
  • kevin
    don't you still need the .each?
  • No, you don't need the .each if you're using a function for the second argument.
  • JC
    thanks Karl ... thanks a lot :)
  • checking the attr() on a custom tag does not behave like checking for the disabled attribute. If I create the custom tag "required" in:

    <input name="username" required="" type="text">

    and get the attribute through jQuery:
    $('input').attr('required');

    Chrome will return true if it is set and false if it is not set.
    The description of this tag states "If we try to get the value of an attribute that has not been set, the .attr() method returns undefined." which is false.

    until this is fixed, here is an easy workaround:

    if($('input').attr('required') === undefined || $('input').attr('required') === false) ...
  • Hi everyone !
    I were unable to change the "action" attribute of a "<form>".

    Assuming the html source :
    ...

    The getter method jQuery("#formId").attr('action') returns correctly the string "myaction.html".
    But the setter method jQuery("#formId").attr('action', 'mynewaction.html') doesn't work.

    In order to work, we seem to have to call the setter method with the attribute in uppercase like : jQuery("#formId").attr('ACTION', 'mynewaction.html').

    It was the only way for me ...



    </form>
  • jade.zhong
    yes, same problem, weird...
  • Hi
    'action' all lower case works normally - it may be that your form contained an input named "action"?
    <form action="one">
    <input name="action" value="two">


    $('form').attr('action') will return 'one' as expected, but $('form').attr('action', 'test') doesn't modify it. If you use 'Action' or 'ACTION' it will change the attribute on the form.

    Only applies to forms, & same issue exists with using hidden inputs named 'method', 'target' etc. Changing the case as you describe works as a workaround</form>
  • Harold Dennison
    same problem here, but this time trying to change "type". "Type" works fine
  • Kyle Dickerson
    I'm seeing the same issue ('ACTION' must be capitalized). I'm using jQuery 1.4.1 and Firefox 3.6.6