dd

XML DOM previousSibling 属性


定义和用法

previousSibling 属性返回选定元素的上一个同级节点(在相同树层级中的下一个节点)。

如果不存在这样的节点,则该属性返回 NULL。

语法

elementNode.previousSibling

提示和注释

注释:Firefox 以及大多数其他的浏览器,会把节点间生成的空的空格或者换行当作文本节点,而 Internet Explorer 会忽略节点间生成的空白文本节点。因此,在下面的实例中,我们会使用一个函数来检查上一个同级节点的节点类型。

元素节点的节点类型是 1,因此如果上一个同级节点不是一个元素节点,它就会移至上一个节点,然后继续检查此节点是否为元素节点。整个过程会一直持续到上一个同级元素节点被找到为止。通过这个方法,我们就可以在所有的浏览器中得到正确的结果。

提示:如需了解更多有关浏览器差异的知识,请在我们的 XML DOM 教程中访问我们的 DOM 浏览器 章节。

实例

下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,并从第一个 <author> 元素取得上一个同级节点:

实例

//check if the previous sibling node is an element node
function get_previoussibling(n)
{
x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("author")[0];
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes[0].nodeValue);

y=get_previoussibling(x);

document.write("
Previous sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);

上面的代码将输出:

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

尝试一下 Demos

nextSibling - 取得节点的下一个同级节点

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>
<script>
//check if the next sibling node is an element node
function get_nextsibling(n)
{
x=n.nextSibling;
while (x.nodeType!=1)
  {
  x=x.nextSibling;
  }
return x;
}

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0];
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes[0].nodeValue);

y=get_nextsibling(x);

document.write("<br>Next sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);
</script>
</body>
</html>