HTML DOM Element setAttribute()
Example
Add a class attribute to an element:
Before:
The Element Object
After:
The Element Object
More examples below.
Description
ThesetAttribute() method sets a new value to an attribute.
If the attribute does not exist, it is created first.
Syntax
Parameters
| Parameter | Description |
| name | Required. The name of the attribute. |
| value | Required. The new attribute value. |
Return Value
| NONE |
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.
UseProperties of the Style Object instead:
NO:
YES:
More Examples
Change an input field to an input button:
Before:
After:
Try it Yourself »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 |

