JS: 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 JS: Get Elements by ID, Tag, Name, Class, CSS Selector

attribute_name and value should be string type.

Returns undefined

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

// set the value of attribute “href” in first link element
var 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.setAttribute("href", "http://example.com");
// is equivalent to
myHtmlEle.href = "http://example.com";

〔►see JS: Get Element's Attribute Value

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

〔►see JS: List/Add/Remove Class Attribute

Basic DOM Methods Topic

  1. JS: Basic DOM Methods
  2. JS: Get Elements by ID, Tag, Name, Class, CSS Selector
  3. JS: Get Element's Attribute Value
  4. JS: Set Element's Attribute Value
  5. JS: List/Add/Remove Class Attribute
  6. JS: Node Type, Node Name, Node Value
  7. JS: Navigate DOM Tree
  8. JS: Add / Remove Event Handler
Like what you read? Buy JavaScript in Depth