Search code examples
jquerytoggleaccordionsiblings

Toggle siblings with jquery


I have problems with toggle() in jquery. See http://jsfiddle.net/rch7L/. When clicking a level-1 header it does exactly what it should, but when clicking a level-2 header it opens all level-3 row and not just the level-3 rows under the level-2 header.

$('tr.level-2, tr.level-3').css("display", "none");

$("tr.level-1").click(function(){
    $(this).siblings('tr.level-2').toggle();
});

$("tr.level-2").click(function(){
    $(this).siblings('tr.level-3').toggle();
});

I've tried using siblings(), but it does not what I want when clicking level-2 headers.


Solution

  • Simply use .nextUntil() method

    LIVE DEMO

    $("tr.level-2").click(function(){
        $(this).nextUntil('tr.level-2').toggle();
    });