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
ThesetAttributeNode() method adds an attribute node to an element.
ThesetAttributeNode() method replaces existing attribute nodes.
ThesetAttributeNode() method returns anAttribute object.
The Difference Between setAttribute() and setAttributeNode()
ThesetAttribute() method replaces attribute values.
ThesetAttributeNode() method replaces Attribute objects.
You must create anAttr object and set theAttr valuebefore adding the attribute to an element.
The result will be the same.
Alternative:
It is easier to useThe setAttribute() Method
See Also:
The removeAttributeNode() Method
Tutorial:
Reference:
Syntax
Parameters
| Parameter | Description |
| node | Required. The attribute node to add. |
Return Value
| Type | Description |
| Object | An Attr object representing the replaced attribute node. 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 |

