2015-09-22 16 views
4

我有兩個div元素與第一個div中的一個按鈕,如下所示。爲什麼我不能使用純JavaScript選擇下一個DIV兄弟?

<div class='my-class'> 
    <div class='other-div'> 
     <button onClick="nextDiv(this);">Click</button> 
    </div> 
</div> 
<div class='my-class'> 
</div> 

以下是我的JavaScript代碼。

function nextDiv(element) { 
     element.closest('.my-class').style.display = 'none'; 
     element.closest('.my-class').nextSibling.style.display = 'block'; 
} 

當我按一下按鈕,我爲什麼可以隱藏的第一要素,但不能與類my-class顯示下一個div元素。相反,我得到以下錯誤:

Uncaught TypeError: Cannot set property 'display' of undefined 

好像我無法選擇使用nextSibling屬性的類my-class下一個div元素。我做錯了什麼?

+4

我敢打賭,'nextSibling'返回文本節點(可以使用'nextElementSibling',以確保下一個元素而是返回)。文本節點沒有'style'屬性,所以'nextSibling.style.display'失敗。 –

+0

由於divs之間的空格 – Hacketo

+0

'.closest()'是一個jQuery函數。它返回一個jQuery對象,而不是DOM元素。 – Barmar

回答

4

nextSibling在這種情況下返回文本節點:

<TextNode textContent=" \n"> 

使用nextElementSibling代替。

MDN: Node.nextSibling

Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get.