XML DOM replaceChild() 方法

定義和用法

replaceChild() วิธีที่จะแทนที่จุดเริ่มต้นลูกของด้วยจุดเริ่มต้นอื่น

ในกรณีที่ประสบความสำเร็จ ฟังก์ชันนี้จะคืนค่าจุดเริ่มต้นที่ถูกแทนที่ ในกรณีที่ล้มเหลวจะคืนค่า NULL

คำสั่ง

elementNode.replaceChild(new_node,old_node)
ตัวแปร รายละเอียด
new_node สำคัญ。กำหนดจุดเริ่มต้นใหม่
old_node สำคัญ。กำหนดจุดเริ่มต้นลูกของที่ต้องแทนที่

ตัวอย่าง

รหัสใต้นี้จะนำ "books.xml" โหลดเข้า xmlDoc และแทนที่จุดเริ่มต้น <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, newNode, newTitle, newText, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.documentElement;
    // สร้างจุดเริ่มต้น book จุดเริ่มต้น title และจุดเริ่มต้นข้อความ
    newNode = xmlDoc.createElement("book");
    newTitle = xmlDoc.createElement("title");
    newText = xmlDoc.createTextNode("Hello World");
    // ใส่ตัวอักษรเข้าสู่จุดเริ่มต้น title
    newTitle.appendChild(newText);
    // ใส่จุดเริ่มต้น title สู่จุดเริ่มต้น book
    newNode.appendChild(newTitle);
    y = xmlDoc.getElementsByTagName("book")[0];
    // ใช้จุดเริ่มต้นนี้ของ book ตอนแรกแทนจุดเริ่มต้น book ตอนแรก
    x.replaceChild(newNode, y);
    z = xmlDoc.getElementsByTagName("title");
    // 輸出所有 title
    for (i = 0; i < z.length; i++) {
        txt += z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試