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 | 必需。指定要替换的子节点。 |
❮ 元素对象