The using of parentNode ,previousSibling

本文通过具体示例展示了如何使用JavaScript进行XML DOM操作,包括获取元素的父节点及同级节点的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<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=x.parentNode;

document.write("Parent node: " + parent.nodeName);

以上代码的输出:

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=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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值