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="#">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

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
Supported in all versions
Safari Safari
18+
Supported in all versions
Edge Edge
80+
11 or earlier ×
IE IE
11+
4 or earlier ×
Opera Opera
48+
7 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
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 .