javascript node.nextSibling 和 ChildNode.nextElementSibling 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24226571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:23:51  来源:igfitidea点击:

What is the difference between node.nextSibling and ChildNode.nextElementSibling?

javascriptdomnodes

提问by Ani

<div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div>

<div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div>

Aren't they the same thing ?

他们不是一回事吗?

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 ?

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

回答by Jules

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

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

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

In this case, document.getElementById('span-01').nextElementSiblingis span-02, but document.getElementById('span-01').nextSiblingis 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).

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