previousSibling和nextSibling返回文本?

run*_*ero 13 html javascript dom

有人可以澄清为什么下面的代码返回#text而不是'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>
Run Code Online (Sandbox Code Playgroud)

Dan*_*Man 29

两者之间的空白也是一个节点.这就是JS库存在的原因.为您提供检索元素兄弟姐妹等选项.

如果HTML源代码如下所示:

<ul>
<li id="A"></li><li id="B"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

它会像你期望的那样工作,因为li元素之间没有空格.

最近,又引入了两个属性,称为 previousElementSiblingnextElementSibling忽略该空格.它适用于IE9及以上,其他主流浏览器现在支持它.

  • 我建议加入[`previousElementSibling`](https://developer.mozilla.org/en-US/docs/Web/API/Element/previousElementSibling)和[`nextElementSibling`](https://开发人员)的提及.mozilla.org/zh-CN/docs/Web/API/Element/nextElementSibling)进入您的答案,以完成它.并且可以在不使用任何使用这些方法的库的情况下完全检索元素兄弟,或者通过在`while()`循环中重复调用`previousSibling`(或`next ...`)来完成. (11认同)