XML DOM setAttributeNode() 方法
❮ 元素物件
示例
下面的程式碼片段載入 "books.xml" 到 xmlDoc 中,併為所有 <book> 元素新增一個 "edition" 屬性
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, y, z, i, newatt, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName('book');
for (i = 0; i < x.length; i++) {
newatt = xmlDoc.createAttribute("edition");
newatt.value = "first";
x[i].setAttributeNode(newatt);
}
// 輸出所有 "edition" 屬性值
for (i = 0; i < x.length; i++) {
txt += "Edition: " + x[i].getAttribute("edition") + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
輸出
Edition: first
Edition: first
Edition: first
Edition: first
自己動手試一試 »
定義和用法
setAttributeNode() 方法新增一個新的屬性節點。
如果元素中已存在同名的屬性,則會被新屬性替換。如果新屬性替換了現有屬性,則會返回被替換的屬性節點,否則返回 null。
語法
elementNode.setAttributeNode(att_node)
引數 | 描述 |
---|---|
att_node | 必需。指定要設定的屬性節點 |
❮ 元素物件