previousSibling和nextSibling返回文本? [英] previousSibling and nextSibling returns text?

查看:218
本文介绍了previousSibling和nextSibling返回文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以澄清为什么下面的代码返回#text而不是'li'

Could someone clarify why the code below returns #text instead of 'li' ?

第一个li的下一个兄弟姐妹不应该是li吗?
同样以前的兄弟姐妹最后一次是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>


推荐答案

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

The whitespace between the two is also a node. That's why JS libraries exist. To give you options like retrieving element siblings.

如果HTML源代码如下所示:

If the HTML source looked like this:

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

它将按照您的期望工作,因为 li之间没有空格元素。

It would work as you expect it, because there's no whitespace between the li elements.

最近,还有两个属性被引入,名为 previousElementSibling nextElementSibling ,忽略该空格。它可以从IE9起,而其他主流浏览器支持一段时间。

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.

这篇关于previousSibling和nextSibling返回文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆