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 tt = document .getElementsByTagName("a")[0];

tt.setAttribute("href", "");

As of , this works in all major browsers.

Using Properties for Standard HTML Attributes

For standard HTML attribute, you can use a property directly.

myHtmlEle.href = "";
// is equivalent to
myHtmlEle.setAttribute("href", "");

When working with XML, such as SVG, you should 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]

DOM How-To

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

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog