HTML DOM Element setAttributeNode()
示例
設定第一個 <h1> 元素的 class 屬性節點
const attr = document.createAttribute("class");
attr.value = "democlass";
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);
之前
你好世界
之後
你好世界
自己動手試一試 »
更多示例見下文。
描述
setAttributeNode()
方法向元素新增屬性節點。
setAttributeNode()
方法替換現有屬性節點。
setAttributeNode()
方法返回一個 Attribute 物件。
setAttribute() 和 setAttributeNode() 之間的區別
setAttribute()
方法替換屬性值。
setAttributeNode()
方法替換 Attribute 物件。
在將屬性新增到元素之前,您必須建立一個 Attr 物件 並設定 Attr 值。
結果將相同。
語法
element.setAttributeNode(node)
引數
引數 | 描述 |
node | 必需。 要新增的屬性節點。 |
返回值
型別 | 描述 |
物件 | 表示被替換屬性節點的 Attr 物件。 如果未替換屬性,則為 null 。 |
更多示例
設定 <a> 元素的 href 屬性節點
const attr = document.createAttribute("href");
attr.value = "https://w3schools.tw";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);
之前
前往 w3schools.com
之後
自己動手試一試 »瀏覽器支援
element.setAttributeNode()
是 DOM Level 1 (1998) 特性。
所有瀏覽器都完全支援。
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |