English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM setAttribute() method

HTML DOM Element Object

setAttribute()The method sets the attribute value of the specified element.

If the attribute already exists, update the value; otherwise, a new attribute will be added using the specified name and value.

UsageremoveAttribute()The method removes an attribute from an element.

Syntax:

element.setAttribute(name, value)
var x = document.getElementsByTagName("H"1")[0];
x.setAttribute("class", "demo");
Test See‹/›

Browser compatibility

All browsers fully support the setAttribute() method:

Method
setAttribute()IsIsIsIsIs

Parameter value

ParameterDescription
nameA string that specifies the name of the attribute to be set to its value
valueA string containing the value to be assigned to the attribute

Technical Details

Return Value:Undefined
Exception:InvalidCharacterError
DOM Version:DOM 2Level

More Examples

Change the input button to an input field:

document.getElementsByTagName("input")[0].setAttribute("type", "text");
Test See‹/›

Set the value of the href attribute of the anchor element:

var x = document.getElementsByTagName("a")[0];
x.setAttribute("href", "https:")//www.oldtoolbag.com/CSS3/");
Test See‹/›

Related References

HTML Tutorial:HTML Attributes

HTML DOM Reference:element .hasAttribute() method

HTML DOM Reference:element .getAttribute() method

HTML DOM Reference:element .removeAttribute() method

HTML DOM Element Object