Set Multiple Attributes at Once Using jQuery

Setting multiple HTML attributes simultaneously in jQuery is a common task that helps keep your JavaScript code clean, concise, and performant. Instead of chaining multiple function calls together, jQuery allows you to pass a single JavaScript object containing key-value pairs directly into its attribute manipulation method. This article explains how to properly use the .attr() method to update multiple attributes at once, highlights practical code examples, and explains when to use alternative methods like .prop().

The .attr() Object Syntax

The standard and most efficient way to set multiple attributes in jQuery is to pass a plain JavaScript object to the .attr() method. In this object, each key represents the attribute name, and the corresponding value represents the attribute's value.

Here is the basic syntax:

$(selector).attr({
    attribute1: "value1",
    attribute2: "value2",
    attribute3: "value3"
});

Practical Example: Updating an Image Element

Consider an <img> element where you need to set the src, alt, title, and a custom CSS class or width simultaneously.

Given the following HTML:

<img id="profile-pic">

You can update all attributes in a single jQuery call:

$('#profile-pic').attr({
    src: '/images/user-avatar.png',
    alt: 'User profile picture',
    title: 'Click to view profile',
    width: '150'
});

Handling Attributes with Hyphens

If an attribute name contains a hyphen—such as custom data-* attributes or aria-* accessibility attributes—you must wrap the attribute name in quotation marks so that JavaScript interprets it as a valid object key:

$('#submit-button').attr({
    'aria-disabled': 'true',
    'data-role': 'primary-action',
    title: 'Submit Form'
});

When to Use .prop() Instead of .attr()

For HTML properties that represent a boolean state—such as checked, disabled, readonly, or selected—it is best practice to use jQuery's .prop() method instead of .attr(). The syntax for setting multiple properties at once is identical to .attr():

$('input[type="checkbox"]').prop({
    disabled: true,
    checked: false
});

Using .prop() ensures that the internal DOM state updates correctly across different browser implementations. For standard HTML attributes like href, src, id, title, and target, continue to use .attr().