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’).find(‘tr’).each(function () {
  2.  var $tr = $(this);
  3.  //do stuff
  4.  
  5.  $tr.find(‘td’).each(function() {
  6.   //do stuff
  7.  })
  8. })

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’)).each(function () {
  2.  var $tr = $(this);
  3.  //do stuff
  4.  
  5.  $($tr.attr(‘cells’)).each(function() {
  6.   //do stuff
  7.  })
  8. })

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

The HTML:

  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>