XML DOM replaceChild() 方法

最后更新于:2022-03-26 22:37:49

XML DOM replaceChild() 方法


XML DOM replaceChild() 方法 Element 对象


定义和用法

replaceChild() 方法替换子节点为其他节点。

如果成功该函数则返回被替换的节点,如果失败则返回 NULL。

语法

elementNode.replaceChild(new_node,old_node)

参数 描述
new_node 必需。规定新节点。
old_node 必需。规定要替换的子节点。


实例

下面的代码片段使用 loadXMLDoc() 把 “books.xml” 载入 xmlDoc 中,并替换第一个 <book> 元素:

实例

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.documentElement;

// 创建 book 元素, title 元素以及 text 节点
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");

// 添加 text 节点到 title 节点中
newTitle.appendChild(newText);
// 添加 title 节点到 book 节点中
newNode.appendChild(newTitle);

y=xmlDoc.getElementsByTagName("book")[0]
// 使用新节点替换第一个 book 节点
x.replaceChild(newNode,y);

z=xmlDoc.getElementsByTagName("title");
for (i=0;i<z.length;i++)
{
document.write(z[i].childNodes[0].nodeValue);
document.write("<br>");
}

尝试一下 »


XML DOM replaceChild() 方法 Element 对象