JQuery every loop in a table row

Possible duplicate:
How to iterate over table rows using jQuery and access some cell values?

I have 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 wrote jQuery to scroll each tr as:

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

But the problem is that it goes through "tr" from "tblTwo", which I don't want. Can someone suggest something to solve?

+51
javascript jquery html-table each tablerow
May 03 '12 at 13:04
source share
3 answers

in jQuery just use

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

using the direct children selector ( > ), you will navigate through immediate descendants (and not all descendants)




in VanillaJS you can use document.querySelectorAll() and walk line by line with forEach()

 [].forEach.call(document.querySelectorAll('#tblOne > tbody > tr'), function(tr) { /* console.log(tr); */ }); 
+147
May 03 '12 at 13:05
source share

Only recommendation:

I would recommend using the DOM table implementation, it is very simple and easy to use, you really don't need jQuery for this task.

 var table = document.getElementById('tblOne'); var rowLength = table.rows.length; for(var i=0; i<rowLength; i+=1){ var row = table.rows[i]; //your code goes here, looping over every row. //cells are accessed as easy var cellLength = row.cells.length; for(var y=0; y<cellLength; y+=1){ var cell = row.cells[y]; //do something with every cell here } } 
+50
May 03 '12 at
source share

Use the immediate children selector > :

 $('#tblOne > tbody > tr') 

Description: selects all direct child elements specified by "child" from the elements specified by "parent".

+18
May 03 '12 at 1:07
source share



All Articles