Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

previousSibling and nextSibling returns text?

Tags:

Could someone clarify why the code below returns #text instead of 'li' ?

Shouldn't the next sibling of first li be li ? Similarly previous sibling of last li be li ?

<body>   <ul>     <!-- comment -->     <li id="A"></li>     <li id="B"></li>     <!-- comment -->   </ul>    <script>     //cache selection of the ul     var ul = document.querySelector('ul');       //What is the nextSibling of the first li?     console.log(ul.querySelector('#A').nextSibling.nodeName); //logs text       //What is the previousSibling of the last li?     console.log(ul.querySelector('#B').previousSibling.nodeName); //logs text   </script> </body> 
like image 763
runtimeZero Avatar asked May 02 '15 11:05

runtimeZero


People also ask

What does nextSibling return?

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

Which of the following methods returns a reference to the next child of the current element's parent?

The read-only nextSibling property of the Node interface returns the node immediately following the specified one in their parent's childNodes , or returns null if the specified node is the last child in the parent element.

What is previousElementSibling?

The Element. previousElementSibling read-only property returns the Element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.


1 Answers

The whitespace between the two is also a node. That's why JS libraries exist. To give you options like retrieving element siblings.

If the HTML source looked like this:

<ul> <li id="A"></li><li id="B"></li> </ul> 

It would work as you expect it, because there's no whitespace between the li elements.

More recently, two more properties have been introduced, called previousElementSibling and nextElementSibling, which ignore that whitespace. It works from IE9 and up, with the other major browsers supporting it for a while now.

like image 121
DanMan Avatar answered Sep 22 '22 12:09

DanMan