tags:

views:

272

answers:

2
$(this).parents('table:first > tbody > tr')

And

$(this).parents('table:first').children('tbody').children('tr')
+12  A: 

The difference is that the first selector is entirely within the parents call, whereas the second one isn't.

Therefore, the first one looks for all parents of this which match table:first > tbody > tr. (In other words, a tr containing this that is in the first table)

The second one will find the parent of this which matches table:first, then find all of the trs directly within tbodys of that parent. (In other words, all of the trs directly inside the parent table)

SLaks
Seems counter intuitive. I read the first exactly as the second. Of course I am too lazy to test.
ChaosPandion
@ChaosPandion: Read them more carefully. You'll see what I mean.
SLaks
+1 - OK, I've looked carefully and I finally got it.
ChaosPandion
I still don't see the difference based on your explanation,though I've stepped into this issue myself..
What don't you understand?
SLaks
I read the first exactly as the second...
Read more carefully. Also, look at the elements matched in the intermediary objects created by the second line (`$(this).parents('table:first')` and `$(this).parents('table:first').children('tbody')`)
SLaks
Doesn't " > tr" also mean "directly inside"?
Yes, but it's in the wrong place. When you put it inside the `parents` call, it looks for parents that match that selector (parents that are `tr`s). When you call `children`, it looks for children of the element you already found. (all children of the `table` that was returned by the `parents` call).
SLaks
Oh I got it now,by your "(parents that are `tr`s)."
+3  A: 

Maybe an example will help... start out with this HTML

<table border=1>
 <thead>
  <th>Outter Table</th>
 </thead>
 <tbody>
  <tr><td>1</td></tr>
  <tr>
   <td>
    <table border=1 width=100>
     <thead>
      <th>Inner Table</th>
     </thead>
     <tbody>
      <tr><td>2a</td></tr>
      <tr><td class="test">2b</td></tr>
      <tr><td>2c</td></tr>
     </tbody>
    </table>
   </td>
  </tr>
  <tr><td>3</td></tr>
 </tbody>
</table>

Apply this script:

$('.test').parents('table:first > tbody > tr').addClass('foo');
$('.test').parents('table:first').children('tbody').children('tr').addClass('bar');

Result:

<table border="1">
 <thead>
  <th>Outter Table</th>
 </thead>
 <tbody>
  <tr class="foo"><td>1</td></tr>
  <tr class="foo">
   <td>
    <table width="100" border="1">
     <thead>
      <th>Inner Table</th>
     </thead>
     <tbody>
      <tr class="bar"><td>2a</td></tr>
      <tr class="bar"><td class="test">2b</td></tr>
      <tr class="bar"><td>2c</td></tr>
     </tbody>
    </table>
   </td>
  </tr>
  <tr class="foo"><td>3</td></tr>
 </tbody>
</table>
fudgey
This is also good!