views:

690

answers:

2

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

+4  A: 

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.

karim79
Doesn't work, too.
Richard Knop
@Richard Knop - I've edited the answer, give it a go.
karim79
Thanks that works :)
Richard Knop
+2  A: 

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.

Jim Schubert
That will toggle all divs with the class .box-content instead of just the one.
karim79
Because there are several containers on the page and I want each .expand-collapse span to toggle only its .box-content, not all on the page.
Richard Knop
sorry, I reread the post and saw there were several per page.
Jim Schubert