Javascript – JQuery closest() help

javascriptjqueryslidetoggle

So I have several containers with this markup on a page:

        <div class="box w400">
            <div class="box-header">
                <span class="expand-collapse">expand/collapse</span>
                <h3>Heading</h3>
            </div>
            <div class="box-content">
                <p>Some content here...</p>
            </div>
        </div>

And I am trying to achieve that after clicking on the .expand-collapse span, the .box-content div will slide up or down (toggle).

Here is the jQuery I'm using, I am trying to achieve this with closest():

        $(document).ready(function() {
            $('.expand-collapse').click(function() {
                $(this).closest('.box-content').slideToggle('slow');
            });
        });

But it is not working for some reason 🙁

Best Answer

Try this:

$(document).ready(function() {
    $('.expand-collapse').click(function() {
        $(this).parent().next('.box-content').slideToggle('slow');
    });
});

That selects the next sibling of the parent div, it does not make use of closest.