1

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?

2 Answers 2

4
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.
        });
     }
});
Sign up to request clarification or add additional context in comments.

3 Comments

@Machine - There's a syntax error in your code. "columns" is undefined.
Oh yeah, forgot to remove that part when I removed unneccessary variables. thanks. Fixed now
I marked this answer correct as i wanted the reference to the outer cell.
3

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          
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.