เมธอด setAttributeNode() ของ XML DOM

คำอธิบายและการใช้งาน

setAttributeNode() วิธีเพิ่มแอตทริบิวต์ใหม่

ถ้ามีแอตทริบิวต์ที่มีชื่อเดียวกันภายในองค์ประกอบ ก็จะแทนที่ด้วยแอตทริบิวต์ใหม่

ถ้าแอตทริบิวต์ใหม่แทนที่แอตทริบิวต์ที่มีอยู่แล้ว ก็จะกลับค่าแอตทริบิวต์ที่ถูกแทนที่ หรือ null ถ้าไม่มี

รูปแบบ

elementNode.setAttributeNode(att_node)
ประกาศ การอธิบาย
att_node ความจำเป็น

ตัวอย่าง

รหัสด้านล่างนี้จะนำ "books.xml" ใส่ xmlDoc และเพิ่มค่าแอตทริบิวต์ "edition" ให้กับทุก element <book>:

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);
    }
    // ออกอากาศทุก "version" ของค่าแอตทริบิวต์
    for (i = 0; i < x.length; i++) {
        txt += "Edition: " + x[i].getAttribute("edition") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試