小码哥的IT人生

XML DOM previousSibling 属性

XML基础 2023-08-12 18:15:19小码哥的IT人生shichen

XML DOM previousSibling 属性

定义和用法

previousSibling 属性可返回某节点之前紧跟的节点(处于同一树层级)

如果没有此节点,那么该属性返回 null。

语法:

nodeObject.previousSibling

提示和注释

注释:Internet Explorer 会忽略节点间生成的空白文本节点(例如,换行符号),而 Mozilla 不会这样做。因此,在下面的例子中,我们会使用一个函数来检查首个子节点的节点类型。

元素节点的节点类型是 1,因此如果首个子节点不是一个元素节点,它就会移至下一个节点,然后继续检查此节点是否为元素节点。整个过程会一直持续到首个元素子节点被找到为止。通过这个方法,我们就可以在 Internet Explorer 和 Mozilla 得到正确的方法。

提示:如需更多有关 IE 与 Mozilla 浏览器之间 XML DOM 的差异的内容,请访问我们的 DOM 浏览器 章节。

实例

在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()

下面的代码片段可从XML文档中 <author> 元素取得前一个同级节点:

//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("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);

输出:

author = Giada De Laurentiis
Previous sibling: title = Everyday Italian

TIY

完整实例【previousSibling - 取得某节点的上一个同级节点】:

<html>
<head>
<script type="text/javascript" src="/demo/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("/demo/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>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

完整实例【nextSibling - 取得某节点的下一个同级节点】:

<html>
<head>
<script type="text/javascript" src="/demo/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("/demo/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>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024