Favorites

DOM Element.setAttribute() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Element.setAttribute()
DOM Element MethodThis method is supported by all modern browsers.
Updated 28th November 2026

The setAttribute() method sets the value of an attribute on an element, adding the attribute if it doesn't exist.

Description

The setAttribute() method sets the value of an attribute, creating it if needed. The value is always converted to a string. For boolean attributes such as disabled and hidden, presence is what counts, so setAttribute('disabled', 'false') still disables the element; use removeAttribute(), toggleAttribute() or the boolean property instead.

Many attributes also have properties, such as el.id and input.value, which are usually simpler. setAttribute() is needed for ARIA attributes, data-* attributes and SVG.

Setting an event handler attribute such as onclick with a string creates inline code, which is blocked by many Content Security Policies; attach listeners with addEventListener() instead. Setting href or src from user input should be checked to avoid javascript: URLs.

Syntax

element.setAttribute(name, value)

Parameters

  • nameThe name of the attribute.
  • valueThe value to set. It is converted to a string.

Return Value

None (undefined).

Example

<button type="button">Bold</button>
const btn = document.querySelector('button');
btn.setAttribute('aria-pressed', 'true');
btn.setAttribute('title', 'Toggle bold');
console.log(btn.outerHTML);

Browser Support

The following information will show you the current browser support for the Element.setAttribute() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee