HTML DOM Element setAttributeNode()
Example
Set the class attribute node of the first <h1> element:
const attr = document.createAttribute("class");
attr.value = "democlass";
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);
Before:
Hello World
After:
Hello World
Try it Yourself »
More examples below.
Definition and Usage
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
element.setAttributeNode(node)
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:
const attr = document.createAttribute("href");
attr.value = "https://www.w3schools.com";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);
Before:
Go to w3schools.com
After:
Try it Yourself »Browser Support
element.setAttributeNode()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |