JS: Set Element's Attribute Value
setAttribute method
The setAttribute
is generic, works in both HTML and XML.
node.setAttribute(AttributeName, value)
-
- set a node/element's attribute.
- Return undefined.
- If the attribute does not exist, it will be created.
The
node
is a HTML/XML node.AttributeName and value should be string.
const tt = document.getElementsByTagName("a")[0]; tt.setAttribute("href", "http://example.com");
As of 2012-04-26, this works in all major browsers.
Set Attributes by Properties: id, class, href, width
If working in HTML (not XML), you can use a property directly for standard HTML attributes.
element.class = value
-
set class value. (must be a string)
When working with the class attribute, there are more convenient methods. [see JS: 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: Get Element's Attribute Value]