PreviousSibling and nextSibling return text?

Can anyone clarify why the code below returns #text instead of 'li'

Shouldn't the next brother be the first li? Similar to the previous brother of the last li li 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> 
+6
source share
1 answer

The space between them is also a node. This is why there are JS libraries. To provide you with options, such as retrieving siblings.

If the HTML source looked like this:

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

It will work as you expect, because there are no spaces between the li elements.

More recently, two more properties have been introduced, called previousElementSibling and nextElementSibling , which ignore these spaces. It runs on IE9 and later, and other major browsers have been supporting it for a while.

+22
source

Source: https://habr.com/ru/post/986409/


All Articles