node.nextSibling 和 ChildNode.nextElementSibling 有什么区别? [英] What is the difference between node.nextSibling and ChildNode.nextElementSibling?

查看:22
本文介绍了node.nextSibling 和 ChildNode.nextElementSibling 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div id="div-01">这里是div-01</div><div id="div-02">这里是div-02</div>

它们不是一回事吗?

两者都返回紧随其后的节点.我阅读了很多文章,但在我看来似乎是同一件事,但不知道在何处使用其中一个和另一个?

Both returning the immediately followed node. I read a lot of articles but seems to me like the same thing, but can't figure where to use one versus other ?

推荐答案

nextElementSibling 总是返回一个元素.nextSibling 可以返回任何类型的节点.它们与您的示例相同,但在其他情况下不同,例如:

nextElementSibling always returns an element. nextSibling can return any kind of node. They are the same for your example, but different in other cases, e.g.:

<p><span id="span-01">Here is span-01</span>
Some text at the top level
<span id="span-02">Here is span-02</span></p>

在这种情况下,document.getElementById('span-01').nextElementSiblingspan-02,但 document.getElementById('span-01').nextSibling 是包含顶层的一些文本"的文本节点(或者,正如@Manngo 在评论中指出的那样,将文本与上面的元素分开的空格 - 似乎有些浏览器将元素和非空白节点之间的空格放入单独的节点中,而其他节点则将其与文本的其余部分合并).

In this case, document.getElementById('span-01').nextElementSibling is span-02, but document.getElementById('span-01').nextSibling is the text node containing "Some text at the top level" (or, as pointed out by @Manngo in the comments, the whitespace that separates that text from the element above -- it seems some browsers put whitespace between elements and non-whitespace nodes into separate nodes, while others combine it with the rest of the text).

这篇关于node.nextSibling 和 ChildNode.nextElementSibling 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆