Using the Jquery closest() function?

Nick picture Nick · Aug 28, 2009 · Viewed 24.4k times · Source

Here's my HTML:

<tr>
    <td class="show_r3c">click here</td>
</tr>
<tr class="r3c">
    <td>This is what I'd like to display</td>
</tr>

And I have currently got this JQuery code,

    $(document).ready(function(){
        $(".r3c").hide();        
        $('.show_r3c').click(function() { 
                         $(this).closest('.r3c').toggle(); 
                         return false; 
        });
   });

For some reason the closest() function isn't working, and it won't toggle the table row .r3c - I've tried using parent and other alternatives but can't get it working either :(

Apologies for the silly question, and something similar to a problem I've had before. Just wondering, What's the best solution for this ?

Thanks!

Answer

Damo picture Damo · Aug 28, 2009

closest() finds the closest parent not the parents-siblings-children.

You want something like:

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { 
        $(this).closest('table').find("tr.r3c").toggle(); return false; 
    });
});