XML DOM insertBefore() 方法
XML基础 2023-08-13 15:02:522小码哥的IT人生shichen
XML DOM insertBefore() 方法
定义和用法
insertBefore() 方法在已有的子节点之前插入一个新的子节点。
该方法返回这个新的子节点。
语法:
elementNode.insertBefore(new_node,existing_node)
参数 | 描述 |
---|---|
new_node | 必需。要插入的节点。 |
existing_node | 必需。已有节点。在此节点之前插入新节点。 |
提示和注释:
注释:Internet Explorer 会忽略节点之间生成的空白文本节点(比如换行字符),而 Mozilla 不这么做。因此,在下面的例子中,我们使用一个函数来检查最后一个子节点的节点类型。
元素节点的节点类型是 1,因此如果最后一个子节点不是元素节点,则移动到上一个节点,并检查这个节点是否是元素节点。这个过程一直会持续到找到最后一个属于元素节点的子节点为止。通过这个方法,在 Internet Explorer 和 Mozilla 中都会得到正确的结果。
如需更多有关 IE 与 Mozilla 浏览器差异的内容,请访问 phpcodeweb 的 XML DOM 教程中的 DOM 浏览器 这一节。
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段创建一个新的 <book> 节点,并把它插到文档中最后一个 <book> 元素之前:
//check if the last childnode is an element node function get_lastchild(n) { x=n.lastChild; while (x.nodeType!=1) { x=x.previousSibling; } return x; } xmlDoc=loadXMLDoc("books.xml"); newNode=xmlDoc.createElement("book"); newTitle=xmlDoc.createElement("title"); newText=xmlDoc.createTextNode("A Notebook"); newTitle.appendChild(newText); newNode.appendChild(newTitle); xmlDoc.documentElement.insertBefore(newNode,get_lastchild(x));
TIY
完整实例【insertBefore() - 在指定节点之前添加节点】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); newNode=xmlDoc.createElement("book"); x=xmlDoc.documentElement; y=xmlDoc.getElementsByTagName("book"); document.write("Book elements before: " + y.length); document.write("<br />"); x.insertBefore(newNode,y[3]); y=xmlDoc.getElementsByTagName("book"); document.write("Book elements after: " + y.length); </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
完整实例【insertBefore() - 在指定子节点之前添加节点】:
<html> <head> <script type="text/javascript" src="/demo/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> //check if the last childnode is an element node function get_lastchild(n) { x=n.lastChild; while (x.nodeType!=1) { x=x.previousSibling; } return x; } xmlDoc=loadXMLDoc("/demo/example/xdom/books.xml"); x=xmlDoc.getElementsByTagName("book")[0]; newNode=xmlDoc.createElement("publisher"); newText=xmlDoc.createTextNode("Clarkson Potter"); newNode.appendChild(newText); x.insertBefore(newNode,get_lastchild(x)); x=x.childNodes; for (i=0;i<x.length;i++) { if (x[i].nodeType==1) { //Process only element nodes document.write(x[i].nodeName); document.write(" - "); document.write(x[i].childNodes[0].nodeValue); document.write("<br />"); } } </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html