Search code examples
javascriptjqueryfindjquery-selectorselement

Why jQuery next can't find the next div?


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.


Solution

  • 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