4

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?

user229044
  • 232,980
  • 40
  • 330
  • 338
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 4
    I would bet that `nextSibling` returns a text node (you could use `nextElementSibling` to ensure the next element is returned instead). Text nodes do not have `style` properties, so `nextSibling.style.display` fails. – Frédéric Hamidi Sep 22 '15 at 14:58
  • because of the space between divs – Hacketo Sep 22 '15 at 14:58
  • `.closest()` is a jQuery function. It returns a jQuery object, not a DOM element. – Barmar Sep 22 '15 at 15:30
  • I don't understand how you're getting that far. `element` is a DOM element, not a jQuery object, so `element.closest()` should complain of trying to call a non-function. If you're trying to do this in plain JS, why do you have jQuery mixed in? – Barmar Sep 22 '15 at 15:31
  • 1
    @Barmar https://developer.mozilla.org/en-US/docs/Web/API/Element/closest – user247702 Sep 22 '15 at 15:43
  • @Stijn Thanks -- I guess the JS designers are trying to put jQuery out of business :) – Barmar Sep 22 '15 at 15:49
  • @FrédéricHamidi: yes it solved the problem using nextElementSibling. You have saved my day! Thanks! and Thank you all for any comment! – O Connor Sep 23 '15 at 07:21

1 Answers1

5

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.

user247702
  • 23,641
  • 15
  • 110
  • 157