Question

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 :(

Was it helpful?

Solution

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.

OTHER TIPS

closest() finds the closes parent element. In your case, the span doesn't have any parent elements with class .box-content. why not just do $('.box-content').slideToggle('slow'); ??

edit: i missed the part where you have several of these on a page. the parent().next should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top