Element.setAttribute() sets the value of an attribute on the element (MDN). If the attribute already exists, the value is updated; otherwise a new attribute is added. Read with getAttribute(); remove with removeAttribute().
Pass the required arguments shown below. Check return values and browser support before you rely on the result.
Syntax
Call el.setAttribute. Start with this line.
JavaScript
el.setAttribute(name, value)
Call
What it does
el.setAttribute(name, value)
Primary signature.
el.setAttribute(...)
Call with the arguments your case needs.
Built into the browser. Call setAttribute(...) on an Element — no import required.
Library declarations
JavaScript
el.setAttribute(name, value)
Parameters
Parameter
Description
qualifiedName
Required. Attribute name (prefix:localName or localName)
value
Required. String (or Trusted Type when enforced)
Return Value
Return Value
Description
*
Always undefined
JavaScript Examples
Example 1 — Set a Safe Attribute
MDN: set name, then read it back with getAttribute().
Always strings. Numbers become string attribute values.
Still sanitize if you later inject those values into HTML.
Compatibility
Browser Support
Element.setAttribute() is Baseline Widely available (MDN, since July 2015). It is not Deprecated, Experimental, or Non-standard. Trusted Types enforcement for unsafe attributes depends on CSP / browser support.
✓ Baseline Widely available
Element.setAttribute()
Set or update any attribute by name. Prefer safe attributes; never feed untrusted strings into XSS sinks.
BaselineWidely available
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
Android WebViewSupported · Modern WebView
Full support
setAttribute()Baseline
Bottom line: Safe and universal for ordinary attributes. Treat event handlers, srcdoc, and script URLs as security-sensitive.
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 (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).
Some attributes (onclick, srcdoc, script src) are XSS injection sinks (MDN). Never pass untrusted strings to those. Prefer safe attributes or Trusted Types.
IDL properties reflect specific attributes and may coerce types. setAttribute() sets any attribute by name as a string (or trusted type).