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]

DOM How-To

Web Scripting Overview

HTML Input

Web Scripting Examples

Web Scripting Misc



Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials