Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 653
Ani Avatar asked Jun 15 '14 04:06

Ani


People also ask

What is the difference between nextSibling and nextElementSibling?

nextSibling vs nextElementSiblingnextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. nextElementSibling returns the next element (not text and comment nodes).

What is sibling in HTML?

Sibling. A sibling is an element that shares the same parent with another element.

How do I get next element in Dom?

The article Whitespace in the DOM contains more information about this behavior. You can use Element. nextElementSibling to obtain the next element skipping any whitespace nodes, other between-element text, or comments.


1 Answers

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

like image 104
Jules Avatar answered Oct 05 '22 21:10

Jules