Search code examples
jqueryxpathjquery-selectorsdom-traversal

How to get immediately following siblings up to next unmatched selector


I have the following table

<table id="table">
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr class="hide"><td>Hidden Item</td></tr>
<tr><td>Item</td></tr>
</table>

on clicking on a visible row, i want to show all the immediately following hidden rows up to the next visible row. The number of hidden rows is not fixed. How can I select immediately following rows up to a specific element?


Solution

  • //Add a class to your visible rows if possible to replace the next selector
    $('tr:visible').click(function() {
        $('.hide').hide();
        $(this).nextUntil(':visible').fadeIn();
    });​
    

    Fiddle

    .nextUntil() Reference


    Adding a show class to the visible rows, you can add a simple toggle effect to it:

    $('.show').click(function() {
        $(this).nextUntil('.show').not('.show').fadeToggle();
    });
    

    Fiddle


    A slightly more elaborated version which toggles the clicked rows' section and hides the rows which were previously open:

    $('.show').click(function() {
        $('.hide').not(
            $(this).nextUntil('.show').not('.show').fadeToggle()
        ).hide();
    });
    

    Fiddle