26

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>
1
  • 9
    Try previousElementSibling and nextElementSibling for just elements.
    – elclanrs
    May 2, 2015 at 11:03

2 Answers 2

53

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.

3
  • 16
    I'd suggest incorporating a mention of previousElementSibling and nextElementSibling into your answer, in order to complete it. And retrieving element siblings can be done entirely without use of any libraries using those methods, or via repeated calls to previousSibling (or next...) within a while() loop. May 2, 2015 at 11:08
  • Support for the xyzElementSibling elements is excellent, even IE9 has it. IE8 doesn't, sadly, and isn't going away nearly as soon as we would all like. :-) May 2, 2015 at 11:15
  • 1
    Yeah, IE8 has one foot in the grave!
    – Ram
    May 2, 2015 at 11:24
2

beter is use 'nextElementSibling' and 'previousElementSibling'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.