jQuery .attr(): Read and Set HTML Attributes

jQuery’s .attr("name") reads an HTML attribute from the first matched element. .attr("name", value) sets the attribute on every element in the selection. You can also pass an object to update several attributes or a callback to compute a value for each element.

Read the first match and write to all matches

The example has two .contact fields with data-state values of primary and backup. The getter returns primary. It returns undefined if the selection is empty or the first match lacks the attribute. Use .map() as in the full example to collect the values from every match.

const $fields = $(".contact");
console.log($fields.attr("data-state")); // primary
$fields.attr("maxlength", 30);
console.log($fields.eq(1).attr("maxlength")); // "30"

The setter adds maxlength to both inputs. Even though the setter takes the number 30, reading this attribute returns the string "30". A setter returns the jQuery collection so you can chain another method. See the official jQuery .attr() reference for argument forms.

Run the example with two text fields

Save the following as a UTF-8 file named example.html and open it in a browser. The example requires an internet connection to load jQuery 4.0.0. On load, the output shows the first value.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery .attr() example</title>
  <style>
    body { font: 1rem/1.6 system-ui, sans-serif; margin: 1rem; }
    label { display: block; }
    input, button { font: inherit; max-width: 100%; box-sizing: border-box; }
    output { display: block; overflow-wrap: anywhere; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
  <h1>jQuery .attr() example</h1>
  <p>
    <label for="primary">Primary contact</label>
    <input id="primary" class="contact" type="text" data-state="primary">
  </p>
  <p>
    <label for="backup">Backup contact</label>
    <input id="backup" class="contact" type="text" data-state="backup">
  </p>
  <button id="apply" type="button">Apply input limit</button>
  <output id="output" aria-live="polite"></output>
  <script>
    $(function () {
      const $fields = $(".contact");
      const first = $fields.attr("data-state");
      const $output = $("#output");
      $output.text("First value: " + first);

      $("#apply").on("click", function () {
        $fields.attr({ title: "Enter a contact name", maxlength: 30 });
        const limits = $fields.map(function () {
          return $(this).attr("maxlength");
        }).get().join(", ");
        $output.text("First value: " + first + " / " +
          "Maximum lengths: " + limits);
      });
    });
  </script>
</body>
</html>

Click Apply input limit. The first value stays primary and the maximum lengths display 30, 30. The click handler passes an object with title and maxlength, so both fields receive both attributes. Inspect each input in your browser’s developer tools, or try typing more than 30 characters after clicking the button.

Compute an attribute for each element

Pass a function in the value position to receive each match’s zero-based index and old attribute value. Run this block in the example’s browser console to append the field’s position to the backup state.

$(".contact").attr("data-state", function (index, oldValue) {
  if (oldValue !== "backup") return;
  return oldValue + "-" + (index + 1);
});

The first field keeps primary; the second changes to backup-2. Returning without a value leaves that match alone. The condition also skips fields that have no old attribute value.

Remove attributes and handle ARIA false

$(".contact").attr("maxlength", null) deletes maxlength from both fields. You can also call .removeAttr(). Setting an empty string leaves the attribute present, so check its presence when inspecting the result.

In jQuery 4.0 and later, passing false removes attributes whose names do not start with aria-. Accessible Rich Internet Applications (ARIA) attributes work differently. .attr("aria-expanded", false) records the string "false" to indicate a collapsed control. Pass null to delete the attribute itself.

Read live checkbox and input state

In <input type="checkbox" checked="">, the presence of checked makes the checkbox checked by default. After a user unchecks it, .prop() returns false for .prop("checked"), while .attr("checked") returns the original empty string in jQuery 4.0.0. Use .val() for the text currently in a field.

Use .css() for CSS styles. To add one class and preserve the others, use .addClass(). Calling .attr("class", value) replaces the entire attribute value.