HTML DOM Element setAttributeNode() 方法

定义和用法

setAttributeNode() 方法向元素中添加指定的属性节点,并返回 Attribute 对象。

如果这个指定的属性已存在,则此方法会替换它。

替代方案:

使用 setAttribute() 方法 更容易。

另请参阅:

参考手册:

getAttributeNode() 方法

removeAttributeNode() 方法

createAttribute() 方法

getAttribute() 方法

setAttribute() 方法

hasAttribute() 方法

Attribute value 属性

HTML DOM Attribute 对象

教程:

HTML 属性

setAttribute() 和 setAttributeNode() 的区别

setAttribute() 方法替换属性值。

setAttributeNode() 方法替换 Attribute 对象。

在将属性添加到元素之前,您必须创建 Attr 对象并设置 Attr 值。

结果将是相同的。

实例

例子 1

设置第一个 <h1> 元素的 class 属性节点:

const attr = document.createAttribute("class");
attr.value = "democlass";

const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);

亲自试一试

设置之前:

Hello World

设置之后:

Hello World

例子 2

设置 <a> 元素的 href 属性节点:

const attr = document.createAttribute("href");
attr.value = "";

const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);

亲自试一试

设置之前:

请访问 sou-xun.com

设置之后:

请访问 sou-xun.com

语法

element.setAttributeNode(newAttr)

参数

参数描述
newAttr必需。表示要添加的属性,或其值需要修改的属性的 Attr 节点。

返回值

类型描述
对象

表示被替换属性节点的 Attr 对象。

如果没有属性被替换,则为 null。

抛出

该方法将抛出含有以下代码的 DOMException 异常:

异常描述
INUSE_ATTRIBUTE_ERRnewAttr 已经是其他 Element 节点的属性集合的成员。
NO_MODIFICATION_ALLOWED_ERR当前的 Element 节点是只读的,不允许修改它的属性。
WRONG_DOCUMENT_ERRnewAttr 的 ownerDocument 属性不同于要设置它的 Element 节点。

浏览器支持

element.setAttributeNode() 是 DOM Level 1 (1998) 特性。

所有浏览器都完全支持它:

ChromeIEEdgeFirefoxSafariOpera
ChromeIEEdgeFirefoxSafariOpera
支持9-11支持支持支持支持