HTML DOM Element setAttribute()
Example
Add a class attribute to an element:
Before:
The Element Object
After:
The Element Object
More examples below.
Description
The setAttribute() method sets a new value to an attribute.
If the attribute does not exist, it is created first.
Syntax
Parameters
The name of the attribute.
The new attribute value.
Return Value
Note
It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute.
Use Properties of the Style Object instead:
NO:
YES:
More Examples
Change an input field to an input button:
Before:
After:
Add a href attribute to an <a> element:
Before:
After:
Try it Yourself »Change the value of the target attribute to "_self":
element.setAttribute("target", "_self");
}
Browser Support
element.setAttribute() is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera | IE |
| Yes | Yes | Yes | Yes | Yes | 9-11 |