JS DOM: Set Attribute

By Xah Lee. Date: . Last updated: .

setAttribute method

The setAttribute is generic, works in both HTML and XML.

node.setAttribute(AttributeName, value)
  • set a node's attribute.
  • Return undefined.
  • If the attribute does not exist, it will be created.

The node is a HTML or XML node.

AttributeName and value should be string.

const xx = document.getElementsByTagName("a")[0];
xx.setAttribute("href", "http://example.com");

As of 2012-04-26, this works in all major browsers.

Set Attributes by Properties

common HTML attributes have properties, you can work directly with it.

element.class = value
set class value. (must be a string)

When working with the class attribute, there are more convenient methods. γ€”see JS DOM: List, Add, Remove Class Attribute〕

element.id = value
set id value. (must be a string)
LinkElement.href = value
set href value. (must be a string)
ImgElement.width = value
set width value. (must be a string)

This

x.href = "http://example.com";

is same as

x.setAttribute("href", "http://example.com");

When working with XML, such as SVG, you should use setAttribute, because it is more general. γ€”see JS DOM: Get Attribute〕

JS DOM Common Task Examples