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元素之间没有空格.
最近,又引入了两个属性,称为 previousElementSibling和nextElementSibling忽略该空格.它适用于IE9及以上,其他主流浏览器现在支持它.