MDN wants to learn about developers like you:

element.setAttribute Redirect 1


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


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


var d = document.getElementById("d1"); 

d.setAttribute("align", "center");


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 should use removeAttribute() instead of elt.setAttribute(attr, null) to remove the attribute.

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).

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 -


Document Tags and Contributors

 Last updated by: Sheppy,