文件:createAttribute() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Document.createAttribute() 方法建立一個新的屬性節點並返回它。建立的物件是一個實現 Attr 介面的節點。DOM 不強制規定透過此方法可以向特定元素新增何種型別的屬性。

注意: 引數中的字串會被轉換為小寫。

語法

js
createAttribute(name)

引數

name

包含屬性名稱的字串。

返回值

一個 Attr 節點。

異常

InvalidCharacterError DOMException

如果 name 值不是有效的 XML 名稱,則丟擲此錯誤;例如,名稱以數字、連字元或句點開頭,或者包含除字母數字字元、下劃線、連字元或句點以外的字元。

示例

js
const node = document.getElementById("div1");
const a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my_attrib")); // "newVal"

規範

規範
DOM
# dom-document-createattribute

瀏覽器相容性

另見