2015-05-02 32 views
6

有人可以澄清爲什麼下面的代碼返回#text而不是'li' ?previousSibling和nextSibling返回文本?

第一個李的下一個兄弟姐妹不應該是李? 同樣以前的李的同胞是李李?

<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

嘗試'previousElementSibling'和'nextElementSibling'只是元素。 – elclanrs

回答

22

兩者之間的空白也是一個節點。這就是JS庫存在的原因。給你選擇像檢索元素兄弟姐妹。

如果HTML源代碼是這樣的:

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

您預期的那樣它的工作,因爲有在li元素之間沒有空格。

最近又引入了兩個屬性,分別稱爲previousElementSiblingnextElementSibling,它忽略了空白。它從IE9開始工作,其他主流瀏覽器支持它一段時間。

+7

我會建議合併提及['previousElementSibling'](https://developer.mozilla.org/en-US/docs/Web/API/Element/previousElementSibling)和['nextElementSibling'](https:// developer.mozilla.org/en-US/docs/Web/API/Element/nextElementSibling)添加到您的答案中,以完成它。並且可以在不使用任何使用這些方法的庫的情況下,或通過在while()'循環內重複調用'previousSibling'(或'next ...')來完成檢索元素的同胞。 –

+0

對xyzElementSibling元素的支持非常好,即使是IE9也是如此。不幸的是,IE8並沒有儘快離開,只要我們都願意。 :-) –

+0

是的,IE8在墳墓裏有一隻腳! – undefined