How do I iterate through table rows and cells in J

2019-01-01 05:00发布

问题:

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?

回答1:

If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), 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(<td>), ignoring which row you\'re on, then 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
}


回答2:

You can consider using jQuery. With jQuery it\'s super-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
    })
})


回答3:

var table=document.getElementById(\"mytab1\");
var r=0;
while(row=table.rows[r++])
{
  var c=0;
  while(cell=row.cells[c++])
  {
    cell.innerHTML=\'[Row=\'+r+\',Col=\'+c+\']\'; // do sth with cell
  }
}
<table id=\"mytab1\">
  <tr>
    <td>A1</td><td>A2</td><td>A3</td>
  </tr>
  <tr>
    <td>B1</td><td>B2</td><td>B3</td>
  </tr>
  <tr>
    <td>C1</td><td>C2</td><td>C3</td>
  </tr>
</table>

In each pass through while loop r/c iterator increases and new row/cell from collection is assigned to row/cell variables. When there\'s no more rows/cells in collection, false is assigned to row/cell and iteration through while loop stops (exits).



回答4:

ES6:

let table = document.querySelector(\"#mytab1\");

for (let row of table.rows) 
{
    for(let cell of row.cells) 
    {
       let value = cell.innerText; // or cell.innerHtml (you can also set value to innerText/Html)
    }
}

Working example here.



回答5:

This solution worked perfectly for me

var table = document.getElementById(\"myTable\").rows;
var y;
for(i = 0; i < # of rows; i++)
{    for(j = 0; j < # of columns; j++)
     {
         y = table[i].cells;
         //do something with cells in a row
         y[j].innerHTML = \"\";
     }
}


标签: javascript