Element.setAttribute()

Adds a new attribute or changes the value of an existing attribute on the specified element.

Syntax

JavaScript
element.setAttribute(name, value);
  • name is the name of the attribute as a string.
  • value is the desired new value of the attribute.

Example

In the following example, setAttribute() is used to set the disabled attribute on a <button>, rendering it disabled.

HTML
<button>Hello World</button>
JavaScript
var b = document.querySelector("button"); 

b.setAttribute("disabled", "disabled");

Notes

When called on an HTML element in an HTML document, setAttribute lower-cases its attribute name argument.

If the specified attribute already exists, then the value of that attribute is changed to the value passed to this function. If it does not exist, then the attribute is created.

Even though getAttribute() returns null for missing attributes, you need to use removeAttribute() instead of elt.setAttribute(attr, null) to remove the attribute. The latter will coerce the null value to the string "null", which is likely not what you want.

Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).

To set an attribute that takes no value, such as the autoplay attribute of an <audio> element, use a null or empty value. For example: elt.setAttribute('autoplay', '')

DOM methods dealing with element's attributes:

Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used)
setAttribute (DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
getAttribute (DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS
hasAttribute (DOM 2) hasAttributeNS - -
removeAttribute (DOM 1) removeAttributeNS removeAttributeNode -

Specification

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/element/setattribute

API DOM Element Élément Method Reference Référence