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;
}

親自試一試