XML DOM setAttributeNode() 方法

定義和用法

setAttributeNode() 方法添加新的屬性節點。

如果元素中已存在同名的屬性,則會將其替換為新屬性。

如果新屬性替換了現有屬性,則返回被替換的屬性節點,否則返回 null。

語法

elementNode.setAttributeNode(att_node)
參數 描述
att_node 必需。規定要設置的屬性節點。

實例

下面的代碼將 "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);
    }
    // 輸出所有“版本”屬性值Output all "edition" attribute values
    for (i = 0; i < x.length; i++) {
        txt += "Edition: " + x[i].getAttribute("edition") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試