javascript nextElementSibling 和 nextSibling 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31097016/
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 13:16:50  来源:igfitidea点击:

Whats the difference between nextElementSibling vs nextSibling

javascript

提问by grasesed

Although I seem to get strange results occasionally these seem to me to be the same so can someone describe the difference?

虽然我似乎偶尔会得到奇怪的结果,但这些在我看来是相同的,所以有人可以描述差异吗?

回答by sjm

'nextSibling' returns the next Node object whereas 'nextElementSibling' returns the next Element object, so probably the real question is what is the difference between a Node & an Element?

'nextSibling' 返回下一个 Node 对象,而 'nextElementSibling' 返回下一个 Element 对象,所以真正的问题可能是 Node 和 Element 之间的区别是什么?

Basically an Element is specified by an HTML Tag whereas a Node is any Object in the DOM, so an Element is a Node but a Node can also include Text Nodes in the form of whitespace, comments, text characters or line breaks. For more info on Elements vs Nodes see this Difference between Node object and Element object?

基本上,元素由 HTML 标签指定,而节点是 DOM 中的任何对象,因此元素是节点,但节点也可以包含空格、注释、文本字符或换行符形式的文本节点。有关元素与节点的更多信息,请参阅节点对象和元素对象之间的差异?

i.e Take the following DOM snippet

即采用以下 DOM 片段

<div id="start"></div>
Me
<p>Hi</p>

Using nextSibling you would get:

使用 nextSibling 你会得到:

console.log(document.getElementById('start').nextSibling); // "\nMe\n"
console.log(document.getElementById('start').nextSibling.nextSibling); // "<p>

Whereas using nextElementSibling you would get:

而使用 nextElementSibling 你会得到:

console.log(document.getElementById('start').nextElementSibling);// "<p>"

Also nextElementSibling is IE10+, being the newer method whereas nextSibling has full browser support

nextElementSibling 也是 IE10+,是较新的方法,而 nextSibling 具有完整的浏览器支持

回答by Manoj Kumar

nextSiblingwill return the next node in the DOM, most probably in current web page scenarios, it is a whitespace but nextElementSiblingwill return only the next element ignoring all the nodes in between, if any.

nextSibling将返回 DOM 中的下一个节点,最有可能在当前的网页场景中,它是一个空格,但nextElementSibling将仅返回下一个元素,忽略其间的所有节点(如果有)。

With respect to the current page. The nextSiblingto the question is a TextNode(Whitespace)but if I want to get the #answersI will use nextElementSibling

相对于当前页面。在nextSibling这个问题是一个TextNode(Whitespace),但如果我想要得到的#answers,我将使用nextElementSibling

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明