如何在JavaScript中遍历表格行和单元格?

How do I iterate through table rows and cells in JavaScript?

如果我有HTML表格...

1
2
3
4
5
6
7
8
9
10
<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>

我将如何遍历所有表行(假设每次检查时行数都可能改变)并从JavaScript内的每一行的每个单元格中检索值?


如果您要遍历每一行(

),知道/识别该行(

),并遍历每一行(

)的每一列(

),那么这就是方法走。

1
2
3
4
5
6
7
8
9
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
   }  
}

如果您只是想遍历单元格(

),而忽略您所在的行,那么这就是方法。

1
2
3
4
5
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
}


您可以考虑使用jQuery。使用jQuery,它非常简单,可能看起来像这样:

1
2
3
4
5
$('#mytab1 tr').each(function(){
    $(this).find('td').each(function(){
        //do your stuff, you can use $(this) to get current cell
    })
})


1
2
3
4
5
6
7
8
9
10
var table=document.getElementById("mytab1");
var r=0; //start counting rows in table
while(row=table.rows[r++])
{
  var c=0; //start counting columns in row
  while(cell=row.cells[c++])
  {
    cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell
  }
}
1
2
3
4
5
6
7
8
9
10
11
<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>

在每次遍历while循环中,循环r / c迭代器都会增加,并且集合中的新行/单元对象将分配给行/单元变量。当集合中没有更多的行/单元时,将false分配给行/单元变量,并在while循环停止(退出)时进行迭代。


尝试

1
2
3
4
5
6
7
for (let row of mytab1.rows)
{
    for(let cell of row.cells)
    {
       let val = cell.innerText; // your code below
    }
}

1
2
3
4
5
6
7
for (let row of mytab1.rows)
{
    for(let cell of row.cells)
    {
       console.log(cell.innerText)
    }
}
1
2
3
4
5
6
7
8
9
10
<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>

1
2
3
4
5
6
7
for ( let [i,row] of [...mytab1.rows].entries() )
{
    for( let [j,cell] of [...row.cells].entries() )
    {
       console.log(`[${i},${j}] = ${cell.innerText}`)
    }
}

1
2
3
4
5
6
7
8
9
10
<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>


更好的解决方案:使用Javascript的本机Array.from()并将HTMLCollection对象转换为数组,然后可以使用标准数组函数。

1
2
3
4
5
6
7
8
var t = document.getElementById('mytab1');
if(t) {
    Array.from(t.rows).forEach((tr, row_ind) => {
        Array.from(tr.cells).forEach((cell, col_ind) => {
            console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
        });
    });
}

您也可以引用tr.rowIndexcell.colIndex,而不是使用row_indcol_ind

我更喜欢这种方法,而不是前两个投票最多的答案,因为它不会使全局变量ijrowcol杂乱无章,因此它提供了干净的模块化代码,不会有任何副作用(或引发皮棉/编译器警告)...而没有其他库(例如jquery)。

如果您要求它在Javascript的旧版本(ES2015之前)中运行,则可以将Array.from进行填充。


如果您想要一种具有功能性的样式,例如:

1
2
3
4
    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1","col2 Val2","col1 Val3","col2 Val4"]

您可以修改HTMLCollection的原型对象(允许以类似于C#中的扩展方法的方式使用),并在其中嵌入一个将集合转换为数组的函数,从而允许使用具有上述样式(例如linq样式)的高阶函数。 C#):

1
2
3
4
5
6
7
    Object.defineProperty(HTMLCollection.prototype,"toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });


这个解决方案对我来说非常有效

1
2
3
4
5
6
7
8
9
10
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 ="";
     }
}


使用单个for循环:

1
2
3
4
5
var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}

您可以使用.querySelectorAll()选择所有td元素,然后使用.forEach()遍历这些元素。可以使用.innerHTML检索它们的值:

1
2
3
4
const cells = document.querySelectorAll('td');
cells.forEach(function(cell) {
  console.log(cell.innerHTML);
})
1
2
3
4
5
6
7
8
9
10
<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>

如果只想从特定行中选择列,则可以使用伪类:nth-child()选择特定的tr,还可以选择与子组合器(>)结合使用(在以下情况下很有用:您在表格中有一张表格):

1
2
3
4
const cells = document.querySelectorAll('tr:nth-child(2) > td');
cells.forEach(function(cell) {
  console.log(cell.innerHTML);
})
1
2
3
4
5
6
7
8
9
10
<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>