DOM: Set Node Attribute Value

By Xah Lee. Date: . Last updated: .
node.setAttribute(attribute_name, 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.

attribute_name and value should be string type.

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.


x.href = "";

is same as

x.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 Node Attribute Value]

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

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

JavaScript in Depth

DOM Scripting Tutorial


Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc