Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. HTML Element .setAttribute()

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

ParameterDescription
attributeNameThe name of the attribute to set, specified as a string.
valueThe 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");

View sample page

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

Chrome Chrome
49+
Firefox Firefox
57+
Safari Safari
18+
Edge Edge
80+
11 or earlier ×
IE IE
11+
4 or earlier ×
Opera Opera
48+
7 or earlier ×
iOS Safari iOS Safari
18+
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .