8

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!

Nick
  • 1,233
  • 13
  • 26
  • 37

3 Answers3

23

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; 
    });
});
Damo
  • 11,410
  • 5
  • 57
  • 74
  • 1
    Since the question was 'Using the Jquery closest() function?' this is the best answer for sure. The other answers are mroe about how to traverse the DOM using jquery without using closest :) – Ryan White Sep 22 '09 at 01:05
13

Try with:

$('.show_r3c').click(function() {
  $(this).parent('tr').next('tr.r3c').toggle();
  return false;
});
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
4

perhaps this would work:

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

    $('.show_r3c').click(function() { 
        $(this).parent().siblings(":first").toggle(); 
        return false; 
    });
});
stefita
  • 1,785
  • 2
  • 20
  • 35