XML DOM setAttribute() 方法
❮ 元素物件
示例
以下程式碼片段將 "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, i, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName('title');
// 為每個 title 元素新增一個新屬性
for (i = 0; i < x.length; i++) {
x[i].setAttribute("edition", "first");
}
// 輸出標題和 edition 值
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue +
" - Edition: " +
x[i].getAttribute('edition') + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
輸出
Everyday Italian - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first
自己動手試一試 »
定義和用法
setAttribute() 方法用於新增一個新屬性。
如果元素中已存在同名屬性,則該屬性的值將被更改為 value 引數的值。
語法
elementNode.setAttribute(name,value)
引數 | 描述 |
---|---|
name | 必需。指定要設定的屬性名稱。 |
value | 必需。指定要設定的屬性值。 |
實際操作演示
❮ 元素物件