Table of Contents

The JavaScript setAttribute() method adds an attribute to an HTML element or updates its value if it already exists. It is useful when a script needs to set an element’s ID, class, accessibility label, custom data, or other markup attribute. This guide explains the syntax, how it relates to DOM properties, and practical examples you can run in a browser.

What Does setAttribute() Do?

setAttribute() is a method of the DOM Element interface. It takes an attribute name and a value. If the named attribute exists, its value is replaced; if it does not exist, the method creates it.

element.setAttribute(name, value);

The method returns undefined. Attribute values are strings. When you pass a number, boolean, or another value, JavaScript converts it to a string.

Basic Example

This example changes a link’s destination and visible label:

<a id="guideLink" href="#">Open the guide</a>

<script>
const link = document.querySelector("#guideLink");

link.setAttribute("href", "https://example.com/guide");
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener");
</script>

After the script runs, the anchor has the new href, target, and rel attributes. In production, use the real destination you intend to link to.

Set an ID, Class, or Title

You can set common HTML attributes with the same method:

<div id="message">Your profile is ready.</div>

<script>
const message = document.querySelector("#message");

message.setAttribute("class", "notice notice-success");
message.setAttribute("title", "Profile status");
console.log(message.getAttribute("class")); // "notice notice-success"
</script>

For attributes that reflect a JavaScript property, property assignment is another option. For example, message.id = "profile-message" updates the reflected id attribute. Use setAttribute() when you specifically want to work with an attribute name and its string value.

Set Boolean Attributes Correctly

HTML boolean attributes are true when present and false when absent. Their text value does not control the state:

<button id="send">Send</button>

<script>
const sendButton = document.querySelector("#send");

sendButton.setAttribute("disabled", ""); // disabled attribute is present
console.log(sendButton.disabled); // true

sendButton.removeAttribute("disabled"); // absent, so the button is enabled
console.log(sendButton.disabled); // false
</script>

For a boolean attribute such as disabled, setting the string "false" still leaves the attribute present and therefore enables the disabled state. Set boolean DOM properties to actual booleans, such as sendButton.disabled = false, or remove the attribute when you want it absent.

Update Accessibility Attributes

Attributes such as aria-label and aria-expanded communicate information to assistive technology. Their values are strings, including the text "true" and "false":

<button id="menuToggle" aria-expanded="false">Menu</button>
<nav id="mainMenu" hidden>...</nav>

<script>
const toggle = document.querySelector("#menuToggle");
const menu = document.querySelector("#mainMenu");

toggle.addEventListener("click", () => {
  const isExpanded = toggle.getAttribute("aria-expanded") === "true";
  toggle.setAttribute("aria-expanded", String(!isExpanded));
  menu.hidden = isExpanded;
});
</script>

The button’s aria-expanded value is updated whenever the menu opens or closes. Keep accessibility state synchronized with the actual interface state.

Use setAttribute() with data-* Attributes

Custom data-* attributes can store string values associated with an element:

<div id="product" class="product">Notebook</div>

<script>
const product = document.querySelector("#product");

product.setAttribute("data-product-id", "sku-204");
product.setAttribute("data-stock", 12);

console.log(product.getAttribute("data-product-id")); // "sku-204"
console.log(product.dataset.productId); // "sku-204"
console.log(product.dataset.stock); // "12"
</script>

The dataset property provides a convenient interface for data attributes. Hyphenated names become camelCase: data-product-id corresponds to dataset.productId. Values remain strings, even if they look like numbers.

Set an Attribute on Several Elements

Query selectors can return multiple elements. Loop through the collection to update each one:

<button class="action">Save</button>
<button class="action">Cancel</button>

<script>
const buttons = document.querySelectorAll(".action");

buttons.forEach((button, index) => {
  button.setAttribute("data-action-number", String(index + 1));
});
</script>

querySelectorAll() returns a static NodeList, and forEach() visits each matched button. The explicit String() conversion makes the intended attribute value clear.

setAttribute() and DOM Properties

Attributes are markup-level values, while properties are JavaScript values on DOM objects. Some properties reflect their corresponding attributes. For example, setting element.id updates the id attribute. Other properties can represent live state that differs from the original markup. An input’s value property, for instance, can change as someone types while its original value attribute remains the default.

<input id="email" value="hello@example.com">

<script>
const email = document.querySelector("#email");

email.setAttribute("value", "new@example.com");
console.log(email.getAttribute("value")); // "new@example.com"
console.log(email.defaultValue); // "new@example.com"
console.log(email.value); // current value, unless changed by the user
</script>

Use setAttribute() for markup attributes. Use properties such as value, checked, and disabled when your code needs the control’s current state.

Set Several Attributes in a Runnable Example

Paste this complete snippet into an HTML file and open it in a browser. Clicking the button updates a status message, its class, and an accessibility attribute:

<button id="statusButton">Mark as complete</button>
<p id="statusText">Not complete</p>

<script>
const button = document.querySelector("#statusButton");
const statusText = document.querySelector("#statusText");

button.addEventListener("click", () => {
  statusText.textContent = "Task complete";
  statusText.setAttribute("class", "complete");
  button.setAttribute("aria-pressed", "true");
});
</script>

This example uses textContent to update visible text and setAttribute() for attributes. If the button can be toggled on and off, update aria-pressed on each click so that it reflects the current state.

Related Attribute Methods

setAttribute() is often used with other Element methods:

  • getAttribute(name) reads an attribute’s string value, or returns null when it is absent.
  • hasAttribute(name) checks whether an attribute is present.
  • removeAttribute(name) removes an attribute.

Together, these methods let JavaScript inspect, create, update, and remove attributes on DOM elements.