.attr() (since 1.0) gets or sets HTML attributes on matched elements — values that appear in markup like title, href, src, and alt.
Syntax
Start with these common calls. Keep them short and readable.
jQuery
// Get (first element only)
var title = $("em").attr("title");
// Set one
$("#link").attr("title", "Market stall");
// Set many
$("#link").attr({ title: "Market stall", rel: "nofollow" });
// Remove
$("#link").attr("title", null);
Call
What it does
.attr(name)
Get attribute on first element
.attr(name, value)
Set attribute; null removes it
.attr({ … })
Set several attributes at once
.attr(name, fn)
Set from function(index, oldValue)
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
name
Used in .attr(name). Get attribute on first element
value
Used in .attr(name, value). Set attribute; null removes it
object
Used in .attr({ … }). Set several attributes at once
fn
Used in .attr(name, fn). Set from function(index, oldValue)
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
Value / undefined
Getters usually return a value from the first matched element, or undefined when nothing applies.
jQuery Examples
Example 1 — Get an Attribute
Read the title of the first em — official getter pattern.
jQuery
var title = $("em").attr("title");
$("#out").text("Title: " + title);
Quotes. Keys may be unquoted unless reserved (quote "class").
Frequently Asked Questions
.attr() gets or sets HTML attributes on matched elements. As a getter it returns the attribute value for the first element only (string or undefined). As a setter it updates attributes on every matched element by name/value, plain object, or callback.
.attr() reads and writes attributes — values from HTML markup (usually strings). .prop() reads and writes live DOM properties. For checked, selected, and disabled, use .prop() or .is(":checked") — not .attr("checked").
No. .attr(name) returns the value for only the first element. Loop with .each() or .map() to read each one. Setters apply to every matched element.
Pass null: .attr("title", null). That matches .removeAttr("title"). Since jQuery 4.0, non-ARIA attributes can also use false — null is the safest cross-version choice.
class is a reserved word in JavaScript. Always write .attr("class", "active"). For class toggles, prefer .addClass(), .removeClass(), or .toggleClass().
Use .attr() for standard HTML attributes (href, src, title, alt, id). Use .data() for app data in jQuery's data cache — it does not require writing data-* attributes for every value.