jQuery .attr() Method

Beginner
8 min read
Updated: Oct 2026
5 examples
Live preview

What Is .attr()?

.attr() (since 1.0) gets or sets HTML attributes on matched elements — values that appear in markup like title, href, src, and alt.

Remember
// 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);
NeedUse
HTML attribute (markup).attr()
Live DOM property.prop()
Input / select value.val()
Remove an attribute.removeAttr() or .attr(name, null)
Toggle CSS classes.addClass() / remove / toggle

How to Use .attr()

Pick the overload that matches get, set-one, set-many, or compute-per-element.

  1. Select the element(s) with a jQuery selector.
  2. Get: .attr("name") — returns the first match (or undefined if unset, since 1.6).
  3. Set one: .attr("name", value) — updates every matched element.
  4. Set many: pass a plain object of name/value pairs.
  5. Compute: .attr("name", function (index, old) { return next; }).
SignatureSinceRole
.attr(name)1.0Get attribute on first element
.attr(name, value)1.0Set attribute; null removes it
.attr({ … })1.0Set several attributes at once
.attr(name, fn)1.1Set from function(index, oldValue)

Pseudocode

Pseudocode
if called as .attr(name):
    return attribute name on first matched element
    // undefined if the attribute was never set (jQuery 1.6+)

if called as .attr(name, value):
    for each matched element:
        if value is null: remove attribute
        else: set attribute name = value

if called as .attr(object):
    for each key in object:
        set that attribute on every matched element

if called as .attr(name, fn):
    for each matched element with index i:
        next = fn(i, currentAttribute)
        if next is not undefined: set attribute to next

Cheat Sheet

Keep these facts handy while reading or writing attribute code.

TopicDetail
Getter scopeFirst element only
Missing attr (1.6+)Returns undefined
Typical typeString (exceptions: some like value, tabindex)
Remove.attr(name, null) or .removeAttr(name)
jQuery 4.0+false removes non-ARIA attrs; ARIA false becomes "false"
class nameAlways quote: .attr("class", …)
Callback skipReturn undefined → leave value unchanged
Form stateUse .prop() / :checked, not .attr("checked")

Live Preview

Get or set the title on the sample link — same APIs as the examples below.

Sample element: the link below. Hover it after a set to see the browser tooltip.

Sample link

Result
Ready — pick an action and click Run.

jQuery Examples

Short, copy-ready snippets. Prefer .prop() when you need live form state.

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);
Try It Yourself

How It Works

  1. Select. $("em") finds emphasis elements.
  2. Get. .attr("title") reads the first match.
  3. Missing. Unset attributes return undefined (1.6+).
  4. Show. Write the string into #out.

Example 2 — Set One Attribute

Pass a name and value to update every matched element.

jQuery
$("#photo").attr("title", "Beijing Brush Seller");
$("#out").text($("#photo").attr("title"));
Try It Yourself

How It Works

  1. Target. Select the element to update.
  2. Set. .attr("title", value) writes the attribute.
  3. Chain. Setters return the jQuery object for chaining.
  4. Verify. Read it back with the getter form.

Example 3 — Set Several Attributes

Pass a plain object to set multiple attributes in one call.

jQuery
$("#photo").attr({
  title: "jQuery Logo",
  rel: "nofollow"
});

$("#out").text(
  $("#photo").attr("title") + " | " + $("#photo").attr("rel")
);
Try It Yourself

How It Works

  1. Object. Each key is an attribute name.
  2. Apply. jQuery sets every pair on the selection.
  3. Quotes. Keys may be unquoted unless reserved (quote "class").
  4. Read. Confirm with two getter calls.

Example 4 — Callback Setter

Compute the new value from the index and the old attribute.

jQuery
$("div.box").attr("id", function (index) {
  return "box-" + index;
});

$("#out").text(
  $("div.box").map(function () { return this.id; }).get().join(", ")
);
Try It Yourself

How It Works

  1. Per element. The function runs once for each match.
  2. Args. index and the old attribute value are passed in.
  3. Return. The return value becomes the new attribute.
  4. Skip. Returning undefined leaves the attribute unchanged.

Example 5 — .attr() vs .prop() on a Checkbox

Clicking changes the property — the attribute stays the initial markup value.

jQuery
$("input").on("change", function () {
  var $input = $(this);
  $("#out").text(
    "attr: " + $input.attr("checked") +
    " | prop: " + $input.prop("checked") +
    " | :checked: " + $input.is(":checked")
  );
}).trigger("change");
Try It Yourself

How It Works

  1. Listen. Update the readout whenever the checkbox changes.
  2. attr. Shows the initial attribute string (does not track clicks).
  3. prop. Boolean live state — prefer this for “is it checked?”.
  4. :checked. Selector form of the same live test.

Edge Cases & Pitfalls

These trips up beginners most often.

boolean

Do not use .attr("checked") for live state

The attribute maps to the initial default, not the current click. Use .prop("checked") or .is(":checked").

syntax

Always quote "class"

class is reserved. Write .attr("class", "active"), or prefer class helper methods.

remove

null removes; ARIA false is special

.attr(name, null) removes. In jQuery 4.0+, false removes non-ARIA attrs but stringifies aria-* to "false".

getter

Getter is first-element only

Loop with .each() or .map() when you need every match’s attribute.

Browser Support

.attr() has been part of jQuery since 1.0. Attribute/property split clarified in 1.6 with .prop(). Works wherever your loaded jQuery build runs.

✓ Stable · jQuery 1.0+

jQuery .attr()

Universal across browsers that run your jQuery version. Prefer current jQuery 3.x+ for consistent attribute handling.

100% jQuery core
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.attr() Universal

Bottom line: Safe for everyday apps. Use .attr() for markup attributes; switch to .prop() for live boolean and form state.

Performance Notes

ApproachCostBest for
One .attr() get/setCheapTypical UI wiring
Object setter (few keys)CheapBatching related attributes
Huge loops calling .attr()CostlyPrefer one selection + callback setter

Attribute access is inexpensive. Prefer one selection and a callback or object setter over repeated queries inside tight loops.

Key Takeaways

  • Role: get/set HTML attributes on matched elements.
  • vs prop: attributes are markup; properties are live DOM state.
  • Forms: name/value, object, or callback — getters are first-only.
  • Remove: .attr(name, null) or .removeAttr(name).

One line: .attr() talks to HTML attributes — use .prop() when you need the live property.

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.

Next: .prop() Method

Learn how properties differ from attributes for live form and DOM state.

.prop() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful