What is the difference between nextElementSibling and nextSibling

Although sometimes strange results seem to me, it seems to me that they are the same, so can someone describe the difference?

+5
source share
2 answers

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

Basically, an element is defined by an HTML tag, while Node is any object in the DOM, so Element is Node, but Node can also contain text nodes in the form of spaces, comments, text characters or line breaks. For more information on Elements vs Nodes, see Is This the Difference Between a Node Object and an Element?

ie Take the following DOM fragment

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

With nextSibling you get:

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

If you use nextElementSibling, you will get:

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

Also nextElementSibling is IE10 +, which is a newer method, while nextSibling has full browser support

+16
source

nextSibling will return the next node to the DOM, most likely in the current scripts of the web page, this is a space, but nextElementSibling will only return the next element, ignoring all nodes between them, if any.

Regarding the current page. nextSibling question to question: TextNode(Whitespace) , but if I want to get #answers , I will use nextElementSibling

enter image description here

enter image description here

+1
source

All Articles