Search code examples
javascriptjquerytraversal

Selecting next two elements after clicking one. (jquery)


I have a table like such:

<table>
<tbody>
<tr class='clickme'>
<td>...</td>
</tr>
<tr class='hidden1'>
<td>...</td>
</tr>
<tr class='hidden2'>
<td>...</td>
</tr>
<tr class='clickme'>
<td>...</td>
</tr>
<tr class='hidden1'>
<td>...</td>
</tr>
<tr class='hidden2'>
<td>...</td>
</tr>
[etc.]
</tbody>
</table>

.hidden1 and .hidden2 are display: none. My goal is to click on clickme and show the next two, but only those two, and only the ones "under" the clickme that I clicked.

I tried closest:

$('.clickme').click(function (e) {
    $(this).closest('.hidden1').remove();
    $(this).closest('.hidden2').remove();
});

No response. Multiple different things. I tried siblings with moderate success, but it only shows the first matches in the entire table. The table could have 100 of these pairs.

$('.clickme').click(function (e) {
        $(this).siblings(".hidden1:first").toggle(); 
        $(this).siblings(".hidden2:first").toggle(); 
    });

I'm stumped, and I feel like it's such an easy solution!


Solution

  • For your markup it is easy to use .nextUntil():

    $(".clickme").click(function() {
        $(this).nextUntil(".clickme").toggle();
    });
    

    DEMO: http://jsfiddle.net/XEF2v/

    If there could be other rows in between you can filter them with .filter():

    $(this).nextUntil(".clickme").filter(".hidden1, .hidden2").toggle();