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:
.attr() method reduces such inconsistencies.Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.
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" />
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');
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.
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.
" + this.id + "')");
});
]]>
]]>