HTML DOM Element setAttributeNode()
Example
Set the class attribute node of the first <h1> element:
attr.value = "democlass";
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);
Before:
Hello World
After:
Hello World
More examples below.
Description
The setAttributeNode() method adds an attribute node to an element.
The setAttributeNode() method replaces existing attribute nodes.
The setAttributeNode() method returns an
Attribute object.
The Difference Between setAttribute() and setAttributeNode()
The setAttribute() method replaces attribute values.
The setAttributeNode() method replaces Attribute objects.
You must create an Attr object and set the Attr value before adding the attribute to an element.
The result will be the same.
Alternative:
It is easier to use The setAttribute() Method
See Also:
The removeAttributeNode() Method
Tutorial:
Reference:
Syntax
Parameters
The attribute node to add.
Return Value
Or
null if no attribute is replaced.
More Examples
Set the href attribute node of a <a> element:
attr.value = "https://www.w3schools.com";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);
Before:
After:
Try it Yourself »Browser Support
element.setAttributeNode() is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera | IE |
| Yes | Yes | Yes | Yes | Yes | 9-11 |