tags:

views:

367

answers:

2

I have the following html structure (which is generated and I can't change):

<table id='tableID'>
<tbody>
    <tr>
     <td>
      <table>...</table>
     </td>
     <td>
      <table>...</table>
     </td>
     <td>
      <table>...</table>
     </td>
    </tr>
    <tr>
     <td>
      <table>...</table>
     </td>
     <td>
      <table>...</table>
     </td>
     <td>
      <table>...</table>
     </td>
    </tr>
    ....
</tbody>
</table>

What i am trying to do is to get all the outer rows and for each column in the outer row manipulate the content. So I've got something like:

var rows = $("#tableID > tbody > tr");
$.each(rows, function(n, row)
{
     var columns = row.children("td");
     if (columns.length > 0) {
          $.each(columns, function (i, column)
          {
               //do stuff
          });
     }
});

The problem I'm having is that the when I get the child tds, it's too greedy and grabs tds from the nested tables too. Does anyone know how I can restrict this so that I only get the tds from the current row of the outer table? Or is there a better way of doing this?

+3  A: 

You may be looping twice unnecessarily. If the idea is to modify each cell that's not part of a nested table, this should work.

var cells = $("#tableID > tbody > tr > td");
$.each(cells, function(n, cell){     
   //do stuff          
});
ichiban
A: 
var rows = $("#tableID > tbody > tr");
rows.each(function(n, row)
{
     $(row).children().each( // td implicit, since tr should only contain td
        function (i, column) {
           //do stuff
           // Note, if you don't need a reference to row inside the function,
           // you can loop directly over the tds by adding > td to the first
           // selector and skip the outer loop.
        });
     }
});
PatrikAkerstrand
@Machine - There's a syntax error in your code. "columns" is undefined.
ichiban
Oh yeah, forgot to remove that part when I removed unneccessary variables. thanks. Fixed now
PatrikAkerstrand
I marked this answer correct as i wanted the reference to the outer cell.
Temple