tags:

views:

22

answers:

1

I have a table structured like this:

<table>
<tr id="id1" class="parent"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>

<tr id="id2" class="parent"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>

.....etc
</table>

As you can see child classes are coresponding to their parent id. Now I want to toggle all the rows which have class names equal to their parent row id whenever parent row is clicked.

I have tried this, perhaps stupid try:) and can't seem to get this working:

  $('tr.parent').click(function() {
    //alert('yay');
    var tog = $(this).attr('id');
    $(this).siblings().hasClass(tog).slideToggle();
    return false;
  });

Thanks.

+2  A: 

Almost there, here ya yo:

$('tr.parent').click(function() {
  var tog = $(this).attr('id');
  $(this).siblings('.' + tog).slideToggle();
  return false;
});

.hasClass() returns a boolean, it checks if an element has a class, you want to filter by the class. .siblings() accepts a selector filter, see here for details.

If the child rows are always after like your example, you can make this a bit more efficient as a forward only lookup with .nextAll() like this:

$('tr.parent').click(function() {
  $(this).nextAll('.' + $(this).attr('id')).slideToggle();
});
Nick Craver
Ah, yes, of course. Works like a charm. Thank you very much as always, Nick.
swan
@kuswantin - Welcome :)
Nick Craver