DOM: Set Element's Attribute Value

By Xah Lee. Date: . Last updated: .

node.setAttribute(attribute_name, value) → set a element's attribute.

The node is a HTML element object. [see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector]

attribute_name and value should be string type.

Return undefined

If the attribute does not exist, it will be created.

// set the value of attribute “href” in first link element
const firstLink = document.getElementsByTagName("a")[0];
firstLink.setAttribute("href", "http://example.com");

As of , this works in all major browsers.

Note: for standard HTML attribute, you can use a property directly.

myHtmlEle.href = "http://example.com";
// is equivalent to
myHtmlEle.setAttribute("href", "http://example.com");

When working with XML, such as SVG, it's better to use setAttribute, because they may not have those attribute as object properties.

[see DOM: Get Element's Attribute Value]

When working with the attribute class, there are more convenient methods.

[see DOM: List/Add/Remove Class Attribute]

Basic DOM Methods Topic

  1. DOM: Basic DOM Methods
  2. DOM: Get Elements by ID, Tag, Name, Class, CSS Selector
  3. DOM: Get Element's Attribute Value
  4. DOM: Set Element's Attribute Value
  5. DOM: List/Add/Remove Class Attribute
  6. DOM: Node Type, Node Name, Node Value
  7. DOM: Navigate DOM Tree
  8. DOM: Add / Remove Event Handler
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon