nb.ag nb.ag - 7 months ago 20
Javascript Question

Show hidden nested tables in jQuery with selectors

I have html with several nested tables (in this example only one is nested):

<table class="toptable" border="1">
<tbody>
<tr class="accordion">
<td>TD1</td>
<td>TD2</td>
<td>TD3</td>
</tr>
<tr>
<td colspan="3">
<table class="nested" border="1">
<tbody>
<tr>
<td>nestedTD1</td>
<td>nestedTD2</td>
</tr>
<tr>
<td>nestedTD3</td>
<td>nestedTD4</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>


My jQuery allows me to show/hide second row of main table by clicking on the first row.

$(function() {
$(".toptable tr:not(.accordion)").hide();
$(".toptable tr:first-child").show();
$(".toptable tr.accordion").click(function(){
$(this).nextAll().fadeToggle();
});
});


Working example is here: http://jsfiddle.net/nbag/pAxry/1/

My problem is that only first row of the nested table is showing. I suppose that problem in the tree traversal on the jquery; I've tried to change
nextAll()
to
find("*")
, but it's not working.

Many thanks for any help!

Answer

I think the problem is in the first selector that hides the table rows. Try this (demo):

$(function () {
    $(".toptable > tbody > tr:not(.accordion)").hide();
    $(".toptable tr:first-child").show();
    $(".toptable tr.accordion").click(function () {
        $(this).next().fadeToggle();
    });
});