.attr()
Categories: General Attributes | Attributes
.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.0attributeName 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:
- Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
- 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.
-
Find the title attribute of the first <em> in the page.
HTML:
<p> Once there was a <em title="huge, gigantic">large</em> dinosaur... </p> The title of the emphasis is:<div></div>
CSS:
em { color:blue; font-weight;bold; } div { color:red; }
Code:
var title = $("em").attr("title"); $("div").text(title);
.attr( attributeName, value )Returns: jQuery
Description: Set one or more attributes for the set of matched elements.
-
.attr( attributeName, value )
version added: 1.0attributeName The name of the attribute to set.
value A value to set for the attribute.
-
.attr( map )
version added: 1.0map A map of attribute-value pairs to set.
-
.attr( attributeName, function(index, attr) )
version added: 1.0attributeName 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.
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:
<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:
$('#greatphoto').attr('alt', 'Beijing Brush Seller');
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, 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!
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:
$('#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.
-
Set some attributes for all <img>s in the page.
HTML:
<img /> <img /> <img /> <div><B>Attribute of Ajax</B></div>
CSS:
img { padding:10px; } div { color:red; font-size:24px; }
Code:
$("img").attr({ src: "/images/hat.gif", title: "jQuery", alt: "jQuery Logo" }); $("div").text($("img").attr("alt"));
-
Set the id for divs based on the position in the page.
HTML:
<div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div>
CSS:
div { color:blue; } span { color:red; } b { font-weight:bolder; }
Code:
$("div").attr("id", function (arr) { return "div-id" + arr; }) .each(function () { $("span", this).html("(ID = '<b>" + this.id + "</b>')"); });
-
Set the src attribute from title attribute on the image.
HTML:
<img title="hat.gif"/>
Code:
$("img").attr("src", function() { return "/images/" + this.title; });
.attr( attributeName, value )
Plugin: ep.modify
Description: Set one or more attributes for the set of matched elements.
-
.attr( attributeName, value )
version added: 6.11.0attributeName The name of the attribute to set.
value A value to set for the attribute.
-
.attr( map )
version added: 6.11.0map A map of attribute-value pairs to set.
The ep.modify plugin overwrites the .attr()
method, is works like the original method but fire an
event named changeAttr.
-
Bind changeAttr event and change an attribute.
HTML:
<div> <input type="checkbox" name="foo"/> <span>This field is required.</span> </span>
Code:
$(':checkbox').on( 'changeAttr', function( event ){ var elem = $(this); if( elem.is(':selected') ){ elem.next().hide(); } else{ elem.next().show(); } }); $(':checkbox').attr( 'selected', true );
Results:
<div> <input type="checkbox" name="foo" selected="true"/> <span style="display:none;">This field is required.</span> </span>
-
changeAttr
version added: 6.11.0Gets fired if an attribute(s) of an element changed.