JavaScript Element setAttribute() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.setAttribute() is an instance method that sets or updates an HTML attribute by name. Learn the MDN name and disabled examples, boolean attributes, data-* and aria-* patterns, XSS injection-sink warnings, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Args

name, value

03

Returns

undefined

04

Boolean

"" or name

05

Security

XSS sinks

06

Status

Baseline widely

Introduction

HTML elements carry attributes—id, class, href, disabled, data-action, and many more. To add or change an attribute from JavaScript, call element.setAttribute(qualifiedName, value). MDN: if the attribute already exists, the value is updated; otherwise a new attribute is added.

On HTML elements in an HTML document, the attribute name is automatically lower-cased when you call setAttribute() (MDN). Non-string values are converted to strings.

💡
Security note (MDN)

Some attributes are injection sinks—values may be parsed as HTML or run as script (e.g. onclick, srcdoc, src on scripts). Never pass untrusted user input to those attributes. Use safe alternatives like addEventListener or sanitized TrustedHTML when Trusted Types are enforced.

This page is part of JavaScript Element. Pair with getAttribute(), hasAttribute(), and removeAttribute().

Understanding the setAttribute() Method

Calling el.setAttribute(name, value) updates the element’s attribute list. To read the result, use getAttribute(); to delete, use removeAttribute().

  • It is an instance method on Element.
  • Takes qualifiedName (string) and value (string or trusted type) (MDN).
  • Returns undefined.
  • Boolean attributes: presence means true; set "" or the attribute name (MDN).
  • For an Attr node first, use setAttributeNode() instead.
  • May throw InvalidCharacterError for invalid attribute names (MDN).

📝 Syntax

General form of Element.setAttribute (MDN):

JavaScript
setAttribute(qualifiedName, value)

Parameters

ParameterTypeDescription
qualifiedNamestringThe attribute name to set (lower-cased on HTML elements in HTML documents) (MDN).
valuestring or trusted typeThe value to assign. Non-strings are converted to strings (MDN).

Return value

TypeDescription
undefinedNo return value (MDN).

Exceptions

  • InvalidCharacterError — invalid characters in qualifiedName (MDN).
  • TypeError — when Trusted Types are enforced and a raw string is passed to a sink attribute (MDN).

Common patterns

JavaScript
const btn = document.querySelector("#hello_button");

// MDN — set a safe attribute
btn.setAttribute("name", "helloButton");

// Boolean attribute (MDN)
btn.setAttribute("disabled", "disabled");
// or btn.setAttribute("disabled", "");

// data-* and aria-*
btn.setAttribute("data-action", "save");
btn.setAttribute("aria-label", "Save document");

// Update existing value
btn.setAttribute("class", "primary large");

⚡ Quick Reference

GoalCode
Set an attributeel.setAttribute("href", "/home")
Set data-idel.setAttribute("data-id", "42")
Enable boolean attrel.setAttribute("disabled", "")
Disable boolean attrel.removeAttribute("disabled")
Read back valueel.getAttribute("data-id")
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Element.setAttribute().

Returns
undefined

No value

Baseline
widely

Since July 2015

Args
name,value

Two strings

Boolean
presence

"" or name

📋 setAttribute() vs IDL properties

setAttribute(name, val)el.disabled = trueel.className = "x"
Works forAny attribute nameSpecific reflected booleansSpecific reflected strings
Value typeAlways string in markupBoolean IDL propertyString property
Boolean attrsSet "" or name; remove to cleartrue / falseN/A
Custom data-*YesN/AN/A (use dataset)
Return valueundefinedAssignment resultAssignment result
Best forGeneric attribute writesToggle disabled/checkedCommon reflected props

Examples Gallery

Examples follow MDN Element.setAttribute() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s safe-attribute demo—set name and toggle disabled.

Example 1 — Set name (MDN)

Set the name attribute on a button and read it back with getAttribute().

JavaScript
const helloButton = document.querySelector("#hello_button");

helloButton.setAttribute("name", "helloButton");
helloButton.innerText = helloButton.getAttribute("name");

console.log(helloButton.getAttribute("name")); // "helloButton"
Try It Yourself

How It Works

MDN: name is an XSS-safe attribute. The button label updates to show the attribute value was set.

Example 2 — Toggle disabled (MDN)

Enable or disable a button with setAttribute and removeAttribute.

JavaScript
const helloButton = document.querySelector("#hello_button");

if (helloButton.disabled) {
  helloButton.removeAttribute("disabled");
} else {
  helloButton.setAttribute("disabled", "disabled");
}

console.log(helloButton.disabled); // true or false
Try It Yourself

How It Works

Boolean attributes are true when present (MDN). Set "disabled" or "" to disable; call removeAttribute() to enable.

📈 Practical Patterns

data-*, class, and accessibility attributes.

Example 3 — Set a data-* Attribute

Store custom metadata on an element for JavaScript or CSS hooks.

JavaScript
const btn = document.querySelector("#save");

btn.setAttribute("data-action", "save");
btn.setAttribute("data-id", "42");

console.log(btn.getAttribute("data-action")); // "save"
console.log(btn.dataset.id);                  // "42"
Try It Yourself

How It Works

setAttribute("data-id", "42") mirrors dataset.id = "42" for data-* names.

Example 4 — Update class

Replace the entire class attribute value in one call.

JavaScript
const card = document.getElementById("card");
// <div id="card" class="muted">

card.setAttribute("class", "highlight active");

console.log(card.getAttribute("class")); // "highlight active"
Try It Yourself

How It Works

For one class at a time, prefer classList.add(). Use setAttribute("class", ...) when you want to replace the full class string.

Example 5 — Set aria-label (Safe Pattern)

Improve accessibility with a safe, non-script attribute instead of event handlers.

JavaScript
const iconBtn = document.querySelector("#icon-btn");

iconBtn.setAttribute("aria-label", "Close dialog");
iconBtn.setAttribute("role", "button");

console.log(iconBtn.getAttribute("aria-label")); // "Close dialog"

// Avoid: iconBtn.setAttribute("onclick", userInput); // XSS sink
Try It Yourself

How It Works

MDN warns that onclick and similar attributes are injection sinks. Use addEventListener for behavior and aria-* for accessible names.

🚀 Common Use Cases

  • Setting id, class, href, or src on dynamic elements.
  • Toggling boolean attributes like disabled, hidden, or checked (MDN).
  • Attaching data-* metadata for JavaScript or CSS selectors.
  • Adding aria-* labels and roles for accessibility.
  • Updating validation state (aria-invalid, aria-expanded).
  • Pairing with getAttribute() and removeAttribute() for full attribute lifecycle.

🧠 How setAttribute() Updates Markup

1

Pass name and value

el.setAttribute("data-id", "42") — qualified name plus string value (MDN).

Args
2

Normalize the name

On HTML elements in HTML documents, the name is lower-cased automatically (MDN).

Name
3

Add or update

If the attribute exists, update its value; otherwise create a new attribute (MDN).

Write
4

Markup reflects the change

Verify with getAttribute() or DevTools; return value is undefined.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, July 2015).
  • Some attributes are XSS injection sinks — never pass untrusted input to onclick, srcdoc, etc. (MDN).
  • Boolean attributes: presence means true; use removeAttribute() to clear (MDN).
  • Do not use setAttribute(name, null) to delete — use removeAttribute() (MDN).
  • For namespaced attributes, use setAttributeNS() (MDN).
  • Related: getAttribute(), hasAttribute(), removeAttribute(), JavaScript hub.

Browser Support

Element.setAttribute() is Baseline Widely available (MDN: across browsers since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.setAttribute()

Set or update any HTML attribute by name — the standard DOM API for dynamic markup.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Supported in legacy IE
Yes
setAttribute() Excellent

Bottom line: Use setAttribute() for generic attribute writes, IDL properties for common reflected fields, and removeAttribute() to delete. Avoid injection sinks with untrusted input.

Conclusion

Element.setAttribute() adds or updates HTML attributes by name. It is Baseline widely available, returns undefined, and pairs naturally with getAttribute() and removeAttribute().

Continue with getAttribute(), removeAttribute(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use setAttribute() for generic attribute names
  • Set boolean attrs with "" or the attribute name (MDN)
  • Sanitize or avoid user input on injection-sink attributes
  • Use addEventListener instead of onclick strings
  • Verify with getAttribute() after setting

❌ Don’t

  • Pass untrusted strings to onclick or srcdoc
  • Use setAttribute(name, null) to delete attributes
  • Expect a useful return value (it is undefined)
  • Rely on uppercase attribute names in HTML documents
  • Confuse attributes with textContent / innerHTML

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.setAttribute()

Set any attribute — add or update.

5
Core concepts
📄 02

Args

name, value

Pair
✍️ 03

Boolean

"" or name

Toggle
04

Baseline

widely available

Status
05

Security

XSS sinks

Caution

❓ Frequently Asked Questions

It sets the value of an attribute on the element. If the attribute already exists, the value is updated; otherwise a new attribute is added (MDN).
No. MDN marks Element.setAttribute() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
undefined. There is no return value (MDN).
Set value to "" or "disabled". Presence means true; call removeAttribute() to turn it off (MDN).
No. IDL properties reflect specific attributes and may coerce types. setAttribute() sets any attribute by name as a string.
Some attributes (onclick, srcdoc, script src) are XSS injection sinks. Never pass untrusted strings to those. Prefer safe attributes like aria-label or sanitized data-* values.
Did you know?

On HTML elements in an HTML document, setAttribute("ID", "x") and setAttribute("id", "x") are equivalent—the browser lower-cases the attribute name before storing it.

Next: setAttributeNode()

Continue with Attr-node attribute workflows.

setAttributeNode() →

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.

8 people found this page helpful