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