27

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

grasesed
  • 915
  • 2
  • 9
  • 15
  • 1
    Does this answer your question? [What is the difference between node.nextSibling and ChildNode.nextElementSibling?](https://stackoverflow.com/questions/24226571/what-is-the-difference-between-node-nextsibling-and-childnode-nextelementsibling) – schlebe May 19 '20 at 05:34

2 Answers2

60

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

i.e 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

Community
  • 1
  • 1
sjm
  • 5,378
  • 1
  • 26
  • 37
  • Whitespace **is** text. –  Jun 28 '15 at 07:02
  • There's a little more to it than that. Nodes have a type stored as a [*nodeType*](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-111237558) property. Elements have a *nodeType* of *1*, there are 11 others (see [*MDN Node.nodeType*](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType)). And the DOM applies to documents other than HTML. – RobG Jun 28 '15 at 07:06
  • Ok thanks that makes sense, so nextElementSibling seems to be the best option for me as I'm building for >IE10 – grasesed Jun 28 '15 at 07:14
2

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

enter image description here

enter image description here

BenM
  • 52,573
  • 26
  • 113
  • 168
m4n0
  • 29,823
  • 27
  • 76
  • 89