XML DOM replaceChild() 方法
XML基础 2023-08-13 15:11:403小码哥的IT人生shichen
XML DOM replaceChild() 方法
定义和用法
replaceChild() 方法用其他节点替换某个子节点。
如成功,该方法返回被替换的节点,如失败,则返回 null。
语法:
elementNode.replaceChild(new_node,old_node)
参数 | 描述 |
---|---|
new_node | 必需。规定新的节点。 |
old_node | 必需。规定要替换的子节点。 |
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段替换 "books.xml" 中第一个 <book> 元素的第一个 <title> 元素:
//check if first child node is an element node function get_firstchild(n) { x=n.firstChild; while (x.nodeType!=1) { x=x.nextSibling; } return x; } xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; //create a title element and a text node newNode=xmlDoc.createElement("title"); newText=xmlDoc.createTextNode("Giada's Family Dinners"); //add the text node to the title node, newNode.appendChild(newText); //replace the last node with the new node x.replaceChild(newNode,get_firstchild(x));
y=xmlDoc.getElementsByTagName("title"); for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write("<br />"); }
输出:
Giada's Family Dinners Harry Potter XQuery Kick Start Learning XML
注释:Internet Explorer 会忽略节点间生成的空白文本节点(例如,换行符号),而 Mozilla 不会这样做。因此,在上面的例子中,我们创建了一个函数来创建正确的子元素。
提示:如需更多有关 IE 与 Mozilla 浏览器差异的内容,请访问 phpcodeweb 的 XML DOM 教程中的 DOM 浏览器 这一节。
TIY
完整实例【replaceChild() - 替换元素节点】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> //check if first child node is an element node function get_firstchild(n) { var x=n.firstChild; while (x.nodeType!=1) { x=x.nextSibling; } return x; } xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); //create a title element and a text node var newNode=xmlDoc.createElement("title"); var newText=xmlDoc.createTextNode("Giada's Family Dinners"); //add the text node to the title node, newNode.appendChild(newText); //replace the first child node with the new node var x=xmlDoc.getElementsByTagName("book")[0]; x.replaceChild(newNode,get_firstchild(x)); //output all titles var y=xmlDoc.getElementsByTagName("title"); for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write("<br />"); } </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html