Flukey
Flukey

Reputation: 6555

select only tr in main table, not nested tables

This question has been asked before, see: jQuery select only tr/td in main table, not nested tables. however it didn't work as a solution for me.

      $("#tablePartners tr:odd").addClass("odd");
      $("#tablePartners tr:even").hide();
      $("#tablePartners tr:first-child").show();

      $("#tablePartners tr.odd").click(function(){
          $(this).next("tr").toggle();
          $(this).find(".arrow").toggleClass("up");
      });

That code works fine for toggling a row on a table, however, it breaks when I have nested tables in the table:

<table id="tablePartners">
    <thead>
        <tr>

            <th>Name</th>
            <th>Description</th>
            <th>Address</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
    <tr>
        <td><a href="#">Partner Name</a></td>
        <td>Random description</td>
        <td>1 Random Street</td>
        <td><div class="arrow"></div></td>
    </tr>
       <tr>
            <td colspan="4">
               <table>
                    <tr>
                        <td><b>Phone</b></td>
                        <td>0123456789</td>
                    </tr>
                    <tr>
                        <td><b>Contact Name</b></td>
                        <td>Jamie</td>
                    </tr>
               </table>

            </td>
        </tr>
    </tbody>
</table>

I've tried doing this to apply the events only to the parent and not nested tables (as suggested in the other question thread), but it didn't work:

  $("#tablePartners>tbody>tr:odd").addClass("odd");
  $("#tablePartners>tbody>tr:even").hide();
  $("#tablePartners>tbody>tr:first-child").show();

  $("#tablePartners>tbody>tr.odd").click(function(){
      $(this).next("tr").toggle();
      $(this).find(".arrow").toggleClass("up");
  });

EDIT: By not working, what I mean is: the toggle event does not work and the odd rows are not hidden. In the first javascript, the toggle worked and the odd rows were hidden but the nest table odd rows were hidden too which I what I don't want.

I think this must be trivial but I've got tunnel vision.

I've put it on jsfiddle: http://jsfiddle.net/9eJ8y/2/

Upvotes: 3

Views: 3175

Answers (1)

Felix Kling
Felix Kling

Reputation: 816404

The problem is that the first code also selects the header row. Using tbody does not, i.e. you have one row less. You could switch odd and even to create the same effect:

$("#tablePartners > tbody > tr:even").addClass("even");
$("#tablePartners > tbody > tr:odd").hide();
$("#tablePartners > tbody > tr:first-child").show();

$("#tablePartners > tbody > tr.even").click(function(){
  $(this).next("tr").toggle();
  $(this).find(".arrow").toggleClass("up");
});

DEMO

Upvotes: 3

Related Questions