Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

이 문서는 아직 자원 봉사자들이 한국어로 번역하지 않았습니다. 함께 해서 번역을 마치도록 도와 주세요!

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

Syntax

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.

<button>Hello World</button>
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