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="#">Yagami Iori's Profile</a> <img id="avatar" src="" alt=""> <button id="btn">Submit</button> <input id="input" type="text">
The following example shows how this works in practice:
// Pattern 1: Overwrite an existing attribute
var link = document.getElementById("link");
link.setAttribute("href", "https://yagami.example.com");
console.log(link.getAttribute("href")); // Outputs "https://yagami.example.com"
// Pattern 2: Add new attributes
link.setAttribute("target", "_blank");
link.setAttribute("data-character", "iori-yagami");
// Pattern 3: Set the src and alt of an image
var avatar = document.getElementById("avatar");
avatar.setAttribute("src", "/img/iori.jpg");
avatar.setAttribute("alt", "Yagami Iori");
avatar.setAttribute("width", "200");
// Pattern 4: Disable a button
var btn = document.getElementById("btn");
btn.setAttribute("disabled", "true");
// Pattern 5: Set the type, placeholder, and maxlength of an input
var input = document.getElementById("input");
input.setAttribute("type", "email");
input.setAttribute("placeholder", "kusanagi_kyo@wp-p.info");
input.setAttribute("maxlength", "50");
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.