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>
nextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With