.attr( attributeName )Returns: String
Description: Get the value of an attribute for the first element in the set of matched elements.
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.
Example:
Find the title attribute of the first <em> in the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|