While developing a JavaScript GridLayout tool at work today, I ran in to a tough spot while traversing tables with jQuery. What I wanted was to only work with the TR and TD elements within the parent table and not any nested tables. At first, I was using code like this (see HTML later for an example of what I was working with):

  1. $(‘#myTable’‘tr’//do stuff
  2. ‘td’//do stuff
  3.  })
  4. })

But the problem with this is that both calls to the ‘find’ method would return all TRs or TDs that are decedents of #myTable, no matter how deep. I could have used a selector that would have found the tbody (the first child of the table not shown in the markup but inserted by the browser) and then found all of the TRs that were children of that and so forth. My issue with that is that I’m not confidant that all browsers insert the tbody element. I’ve read online that they are supposed to, but for real, who knows? And I don’t like programming browser-specific stuff.

At any rate, the easiest way I found to accomplish this is to pass the table.rows and rows.cells collections to the jQuery constructor ala:

  1. $($(‘#myTable’).attr(‘rows’//do stuff
  3.  $($tr.attr(‘cells’//do stuff
  4.  })
  5. })

And boom, no nested tables return. Wonderful. At least I think that’s what I did. It’s been a few hours now….


  1. <table id="myTable">
  2.  <tr>
  3.   <td>stuff</td>
  4.   <td>things</td>
  5.  </tr>
  6.  <tr>
  7.   <td colspan="2">
  8.    <table>
  9.     <tr>
  10.      <td>cat</td>
  11.      <td>dog</td>
  12.     </tr>
  13.    </table>
  14.   </td>
  15.  </tr>
  16. </table>