tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system
Contents:

.attr( attributeName )

Returns: String

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

.attr( attributeName )

version added: 1.0
attributeName
The 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.

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

.attr( attributeName, value )

version added: 1.0
attributeName
The name of the attribute to set.
value
A value to set for the attribute.

.attr( map )

version added: 1.0
map
A map of attribute-value pairs to set.

.attr( attributeName, function(index, attr) )

version added: 1.1
attributeName
The 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.
<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 1

Set some attributes for all <img>s in the page.
    $("img").attr({ 
          src: "/images/hat.gif",
          title: "jQuery",
          alt: "jQuery Logo"
        });
    $("div").text($("img").attr("alt"));
The output of the code above will be:

Example 1 - Full source:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>  
  <script>
  $(document).ready(function(){
    $("img").attr({ 
          src: "/images/hat.gif",
          title: "jQuery",
          alt: "jQuery Logo"
        });
    $("div").text($("img").attr("alt"));
  });
  </script>
  <style>
  img { padding:10px; }
  div { color:red; font-size:24px; }
  </style>
</head>
<body>
  <img />
  <img />
  <img />
  <div><B>Attribute of Ajax</B></div>
</body>
</html>

Example 2

Disables buttons greater than the 1st button.
$("button:gt(1)").attr("disabled","disabled");
The output of the code above will be:

Example 2 - Full source:

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

Example 3

Sets id for divs based on the position in the page.
    $("div").attr("id", function (arr) {
          return "div-id" + arr;
        })
        .each(function () {
          $("span", this).html("(ID = '<b>" + this.id + "</b>')");
        });
The output of the code above will be:

Example 3 - Full source:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
    $("div").attr("id", function (arr) {
          return "div-id" + arr;
        })
        .each(function () {
          $("span", this).html("(ID = '<b>" + this.id + "</b>')");
        });
  });
  </script>
  <style>
  div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }
  </style>
</head>
<body>
  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>
</body>
</html>

Example 4

Sets src attribute from title attribute on the image.
    $("img").attr("src", function() { 
          return "/images/" + this.title; 
        });
The output of the code above will be:

Example 4 - Full source:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>  
  <script>
  $(document).ready(function(){    
    $("img").attr("src", function() { 
          return "/images/" + this.title; 
        });
  });
  </script>
</head>
<body>
  <img title="hat.gif"/>
  <img title="hat-old.gif"/>
  <img title="hat2-old.gif"/>
</body>
</html>
Was this information helpful?
   

Comments