HTML Element .setAttribute() Since: DOM Level 1(1998)
Sets the specified attribute on an HTML element. If the attribute already exists, its value is overwritten; if it does not exist, a new attribute is added.
Syntax
element.setAttribute("attributeName", "value");
Parameters
| Parameter | Description |
|---|---|
| attributeName | The name of the attribute to set, specified as a string. |
| value | The value to assign to the attribute, specified as a string. |
Sample Code
<a id="link" href="#">Link</a> <img id="photo" src="" alt="">
var link = document.querySelector("#link");
// Overwrite an existing attribute.
link.setAttribute("href", "https://example.com");
// Add new attributes.
link.setAttribute("target", "_blank");
link.setAttribute("data-type", "external");
// Set the src of an image.
var img = document.querySelector("#photo");
img.setAttribute("src", "/img/photo.jpg");
img.setAttribute("alt", "Landscape photo");
Description
element.setAttribute() is a method that sets an attribute on an HTML element. If the attribute does not exist, it is newly added; if it already exists, its value is overwritten.
To retrieve the value of an attribute, use element.getAttribute(). To remove an attribute, use removeAttribute().
When manipulating the class attribute, it is safer to use element.classList instead of setAttribute("class", "..."). Using element.setAttribute() to set class will overwrite all existing classes.
element.setAttribute() is covered in more detail in the tutorial article Identify an element by its id and manipulate its attributes. Feel free to check it out.
Browser Compatibility
4 or earlier ×
7 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.