Search code examples
javascripthtmlclosestnextsibling

Why cannot I select the next DIV sibling using pure JavaScript?


I have two div elements with one button in the first div as follows.

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

Below is my JavaScript code.

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

When I click on the button, why can I hide the first element but cannot show the next div element with the class my-class. Instead, I get the following error:

 Uncaught TypeError: Cannot set property 'display' of undefined

It seems like I cannot select the next div element of the class my-class using the nextSibling property. What did I do wrong?


Solution

  • nextSibling returns a text node in this case:

    <TextNode textContent=" \n">
    

    Use nextElementSibling instead.

    From 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.