XML DOM replaceChild() 方法
❮ 元素物件
示例
下面的程式碼片段載入 "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("A Notebook");
// 將文字節點新增到 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;
}
上面程式碼的輸出將是
A Notebook
Harry Potter
XQuery Kick Start
學習 XML
自己動手試一試 »
定義和用法
replaceChild() 方法用一個新節點替換一個子節點。
此函式成功時返回被替換的節點,失敗時返回 NULL。
語法
elementNode.replaceChild(new_node,old_node)
引數 | 描述 |
---|---|
new_node | 必需。指定新節點。 |
old_node | 必需。指定要替換的子節點。 |
❮ 元素物件