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", "http://example.com");

As of , this works in all major browsers.

Using Properties for Standard HTML Attributes

For standard HTML attribute, you can use a property directly.

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 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]

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js