定义和用法
previousSibling 属性返回选定节点的上一个同级节点(在相同树层级中的前一个节点)。
如果不存在这样的节点,则该属性返回 null。
注意:
var y=get_previoussibling(x);
代码实例中前面加上了(get_)
语法:
elementNode.previousSibling
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
<?xml version="1.0" encoding="ISO-8859-1" ?> - <!-- Copyright w3school.com.cn --> - <!-- W3School.com.cn bookstore example --> - <bookstore> - <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> - <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> - <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> - <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> </bookstore>
下面的代码片段获取 XML 文档中第一个 <author> 元素的上一个同级节点:
<html> <head> <script type="text/javascript" src="/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> //check if the previous sibling node is an element node function get_previoussibling(n) { var x=n.previousSibling; while (x.nodeType!=1) { x=x.previousSibling; } return x; } xmlDoc=loadXMLDoc("/example/xdom/books.xml"); var x=xmlDoc.getElementsByTagName("author")[0]; document.write(x.nodeName); document.write(" = "); document.write(x.childNodes[0].nodeValue); var y=get_previoussibling(x); document.write("<br />Previous sibling: "); document.write(y.nodeName); document.write(" = "); document.write(y.childNodes[0].nodeValue); </script> </body> </html>
输出
author = J K. Rowling
Previous sibling: title = Harry Potter
nextSibling——获取节点的下一个同级节点
<html> <head> <script type="text/javascript" src="/example/xdom/loadxmldoc.js"> </script> </head> <body> <script type="text/javascript"> //check if the next sibling node is an element node function get_nextsibling(n) { var x=n.nextSibling; while (x.nodeType!=1) { x=x.nextSibling; } return x; } xmlDoc=loadXMLDoc("/example/xdom/books.xml"); var x=xmlDoc.getElementsByTagName("title")[0]; document.write(x.nodeName); document.write(" = "); document.write(x.childNodes[0].nodeValue); var y=get_nextsibling(x); document.write("<br />Next sibling: "); document.write(y.nodeName); document.write(" = "); document.write(y.childNodes[0].nodeValue); </script> </body> </html>
输出
title = Harry Potter
Next sibling: author = J K. Rowling