Why can't I select the next div brother using pure JavaScript?

I have two elements divwith one button in the first div, as shown below.

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

The following is the JavaScript code.

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

When I click 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 I cannot select the next div element of the class my-classusing the nextSibling property. What have I done wrong?

+4
source share
1 answer

nextSibling returns the text node in this case:

<TextNode textContent=" \n">

Use instead nextElementSibling.

MDN: Node.nextSibling

, Gecko, . a node, , , Node.firstChild Node.previousSibling node, , .

+4

Source: https://habr.com/ru/post/1608514/


All Articles