DOM:element.setAttribute
From MDC
Contents |
[edit] Summary
Adds a new attribute or changes the value of an existing attribute on the specified element.
[edit] Syntax
element.setAttribute(name, value);
-
nameis the name of the attribute as a string. -
valueis the desired new value of the attribute.
[edit] Example
var d = document.getElementById("d1");
d.setAttribute("align", "center");
[edit] Notes
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 should use removeAttribute() instead of elt.setAttribute(attr, null) to remove the attribute.
Using setAttribute() to modify certain attributes, most notably value in XUL and HTML and selected in HTML, 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).
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 | - |
[edit] Specification
DOM Level 2 Core: setAttribute (introduced in DOM Level 1 Core)