tags:

views:

392

answers:

2

If I have an HTML table...say

<div id="myTabDiv">
<table name="mytab" id="mytab1">
  <tr> 
    <td>col1 Val1</td>
    <td>col2 Val2</td>
  </tr>
  <tr>
    <td>col1 Val3</td>
    <td>col2 Val4</td>
  </tr>
</table>
</div>

How would I iterate through all table rows (assuming the number of rows could change each time I check) and retrieve values from each cell in each row from within Javascript?

+6  A: 

if you want to go through each row knowing the row and then iterate through each column of each row then this is the way to go

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i ++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j ++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

if you just want to go through the cells ignoring which row you're on this is the way to go

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i ++) {
     //iterate through cells
     //cells would be accessed using the "cell" variable assigned in the for loop
}
John Hartsock
probably `row.cells[j]; j++)`, right?
maerics
thank you...copy paste error.
John Hartsock
A: 

You can consider using jquery. With jquery it is sueper-easy and might look like this:

$('#mytab1 tr').each(function(){
    $(this).find('td').each(function(){
        //do your stuff, you can use $(this) to get current cell
    })
})
Lukasz Dziedzia
Can't use jquery...company doesn't allow it. Don't ask why.
GregH