jQuery each loop in table row

ANP picture ANP · May 3, 2012 · Viewed 390.6k times · Source

I am having something like:

<table id="tblOne">
            <tbody>
                <tr>
                    <td>
                        <table id="tblTwo">
                            <tbody>
                                <tr>
                                    <td>
                                        Items
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        Prod
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>
                        Item 1
                    </td>
                </tr>
                <tr>
                    <td>
                        Item 2
                    </td>
                </tr>
            </tbody>
        </table>

I have written jQuery to loop through each tr like:

$('#tblOne tr').each(function() {...code...});

But problem is that it loops through the "tr" of "tblTwo" also which I don't want. Can anyone please suggest something to solve this?

Answer

Fabrizio Calderan picture Fabrizio Calderan · May 3, 2012

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), example with three rows:

$('table > tbody  > tr').each(function(index, tr) { 
   console.log(index);
   console.log(tr);
});

Result:

0
<tr>
1 
<tr>
2
<tr>

In VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
    /* console.log(index); */
    /* console.log(tr); */
});