您的位置:首页 > Web前端 > Node.js

The using of parentNode ,previousSibling

2015-04-13 14:18 239 查看
<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>
</pre><pre code_snippet_id="642452" snippet_file_name="blog_20150413_3_9305943" name="code" class="html">



实例

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

下面的代码片段获取 "books.xml" 中第一个 <title> 元素的父节点:
xmlDoc=loadXMLDoc("books.xml");

var x=xmlDoc.getElementsByTagName("title")[0];
var parent=[code]x.parentNode
;

document.write("Parent node: " + parent.nodeName);[/code]

以上代码的输出:
Parent node: book



定义和用法

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

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

语法:

elementNode.previousSibling



提示和注释

注释:Internet Explorer 会忽略节点之间生成的空白文本节点(比如换行字符),而 Mozilla 不这么做。因此,在下面的例子中,我们用一个函数来检测上一个同级节点的节点类型。

元素节点的节点类型是 1,因此假如上一个同级节点不是元素节点,则移动到上一个节点,并检测该节点是否是元素节点。这个过程一直持续到找到上一个同级节点为止。这种方法可以确保在 Internet Explorer 和 Mozilla 都获得正确的结果。

如需更多有关 IE 与 Mozilla 浏览器差异的内容,请访问 W3School 的 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=[code]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);[/code]

以上代码的输出:
author = Giada De Laurentiis
Previous sibling: title = Everyday Italian



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐