DOM Element.setAttribute() Method
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
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.
Desktop





Tablets & Mobile





