3

I want to create a page for FAQs and used jQuery to show each answer. But it does not work.
The format of each question-answer is like this:

<div><a href="javascript:void(0)" class="expand">First Question</a></div>
<div class="answer" style="display:none">First Answer</div>  

And the jQuery code that I have used is:

$(".expand").click(function(){
    $(this).next('.answer').slideToggle();
});

Is it wrong? You can see its jsFiddle too.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127

3 Answers3

19

The two elements are not at the same level for next() to work.

Try this:

$(".expand").click(function(){
    $(this).parent().next('.answer').slideToggle();
});

Here is an updated fiddle for your reference

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • How to use selectors for this - http://jsfiddle.net/8HH9L/4/ I want to hide selected rows in table after the button... – Ninad Jul 31 '14 at 11:39
3

Because jQuery.next() grabs siblings, the div you're trying to get is the parent's sibling, not the sibling.

Cameron Askew
  • 1,403
  • 1
  • 12
  • 20
2

Well $(this) is the a-element, and there are no siblings to that element. If you want the div, use parent:

$(this).parent().next()
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29