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.
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 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.
It is easier to use The setAttribute() Method
The removeAttributeNode() Method
element.setAttributeNode(
node)
Parameter | Description |
node | Required. The attribute node to add. |
Type | Description |
Object | An Attr object representing the replaced attribute node. Or null if no attribute is replaced. |
Set the href attribute node of a <a> element:
const attr = document.createAttribute("href");
attr.value = "https://www.91xjr.com";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);
Before:
Go to 91xjr.com
After:
Try it Yourself »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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!