Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select only tr/td in main table, not nested tables.

Tags:

jquery

I currently have a table with a nested table in it:

   <table class="datagrid" id="report">
       <thead>
         <tr>
          <th>item1</th>
          <th>item2</th>
         </tr>
       </thead>
       <tbody>
       <tr class="odd"> <-- on click from this level only 
        <td></td>  
        <td></td>
       </tr>
       <tr>
        <td colspan="2">
         <table>
          <tr class="odd"> <-- not to be fired here
           <td></td> 

etc table structure.

I am currently using the following jQuery, which fires on every tr regardless of the table level. How do I change it to only fire on the first level?

 $(document).ready(function(){
            $("#report tr:not(.odd)").hide();
            $("#report tr:first-child").show();

            $("#report tr.odd").click(function(){
                $(this).next("#report tr").fadeToggle(600);
            });
        });
like image 636
TheAlbear Avatar asked Mar 04 '10 16:03

TheAlbear


3 Answers

Use the child selector > to only select those tr elements that are a child of the report table’s tbody, for example:

$("#report > tbody > tr.odd")
like image 153
Gumbo Avatar answered Sep 22 '22 16:09

Gumbo


with this solution it does not matter whether you have a tbody tag in between:

$('table').find('tr:first').parent().children()
like image 30
nerdess Avatar answered Sep 23 '22 16:09

nerdess


You use the > selector to target only the direct descendant of an element. You have to target the implicit tbody element inside the table also:

$('#report>tbody>tr.odd')
like image 30
Guffa Avatar answered Sep 21 '22 16:09

Guffa