37

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

1 Answer 1

79

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>

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

1
  • 3
    Actually, they may not be the same in the sample. Firefox sees the line break between the two div elements as a text node (white space), so .nextSibling would return that. This is a pain, but technically acceptable.
    – Manngo
    Commented Jul 2, 2018 at 2:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.