简体   繁体   中英

Whats the difference between nextElementSibling vs nextSibling

尽管有时候我似乎得到奇怪的结果,但在我看来这些似乎是一样的,所以有人可以描述这些差异吗?

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

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?

ie Take the following DOM snippet

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

Using nextSibling you would get:

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

Whereas using nextElementSibling you would get:

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

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

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

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

在此处输入图片说明

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM