docs.rodeo

MDN Web Docs mirror

Element: setAttribute() method

{{APIRef("DOM")}} 

The setAttribute() method of the {{domxref("Element")}}  interface sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

To get the current value of an attribute, use {{domxref("Element.getAttribute", "getAttribute()")}} ; to remove an attribute, call {{domxref("Element.removeAttribute", "removeAttribute()")}} .

If you need to work with the {{domxref("Attr")}}  node (such as cloning from another element) before adding it, you can use the {{domxref("Element.setAttributeNode()", "setAttributeNode()")}}  method instead.

Syntax

setAttribute(name, value)

Parameters

Boolean attributes are considered to be true if they’re present on the element at all. You should set value to the empty string ("") or the attribute’s name, with no leading or trailing whitespace. See the example below for a practical demonstration.

Since the specified value gets converted into a string, specifying null doesn’t necessarily do what you expect. Instead of removing the attribute or setting its value to be null, it instead sets the attribute’s value to the string "null". If you wish to remove an attribute, call {{domxref("Element.removeAttribute", "removeAttribute()")}} .

Return value

None ({{jsxref("undefined")}} ).

Exceptions

Examples

In the following example, setAttribute() is used to set attributes on a {{HTMLElement("button")}} .

HTML

<button>Hello World</button>
button {
  height: 30px;
  width: 100px;
  margin: 1em;
}

JavaScript

const button = document.querySelector("button");

button.setAttribute("name", "helloButton");
button.setAttribute("disabled", "");

{{ EmbedLiveSample('Examples', '300', '50') }} 

This demonstrates two things:

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN