XML DOM setAttribute() 方法

定義和用法

setAttribute() 方法添加新屬性。

如果元素中已存在同名的屬性,則將其值更改為 value 參數的值。

語法

elementNode.setAttribute(name,value)
參數 描述
name 必需。規定要設置的屬性的名稱。
value 必需。規定要設置的屬性的值。

實例

例子 1

下面的代碼將 "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");
    }
    // 輸出 title 和 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;
}

親自試一試

例子 2

通過 setAttribute() 更改屬性的值:

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('book');
    for (i = 0; i < x.length; i++) { 
        x.item(i).setAttribute("category", "BESTSELLER");  
    }
    // 輸出所有屬性值
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute('category') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

親自試一試