tags:

views:

654

answers:

2

I have some simple tables (multiple, all with class="parent") with multiple <tr> rows. The <td> cells within these rows have tables of their own. I'm trying to target the <tr> rows of the first (parent) tables, like so:

HTML:

<table class="parent"> 
  <tr> <-- match with :first 
    <td> 
      <table> 
        <tr><td></td></tr> 
        <tr><td></td></tr> 
      </table> 
    </td> 
  </tr> 
  <tr> <-- match with :last 
    <td> 
      <table> <-- so ignore this child ..
        <tr><td></td></tr> 
        <tr><td></td></tr> <-- .. and do NOT match this <tr> with :last 
      </table> 
    </td> 
  </tr> 
</table>

jQuery:

$('table.parent').each(function() { 
  $(this).find('tr:first').dostuff(); 
  $(this).find('tr:last').dostuff(); 
});

The :first <tr> works fine, since that's always the <tr> of the parent. But when I try to select the :last <tr>, it'll match the last <tr> of the nested table, and not the last <tr> of the parent table. How can I tell jQuery to only look at the <tr>s that are in the parent table, and don't search any further in possible children tables?

+2  A: 

Instead of .find() (which finds all descendents) try .children() which finds only direct children:

$(this).children('tr:first').dostuff();
VoteyDisciple
+5  A: 

I would suggest modifying your selector slightly to ensure that it works on browsers that append a <tbody> to tables (like Firefox and Chrome):

//tested
$('table.parent > tbody').each(function() {
   $(this).children('tr:first').text('hello').css('background-color', 'red');
   $(this).children('tr:last').text('hello').css('background-color', 'red');
});
karim79