如果我有一个HTML表

<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>

我将如何遍历所有表行(假设行数可以改变每次检查)和检索值从每个单元格在每一行从JavaScript?


当前回答

这是一个使用childNodes和HTMLCollection的不同方法

    <script>
        var tab = document.getElementsByTagName("table")
        for (var val of tab[0].childNodes[1].childNodes.values())
            if (HTMLCollection.prototype.isPrototypeOf(val.children)) {
                for (var i of val.children) {
                    console.log(i.childNodes[0])
                }
            }
    </script>

其他回答

您可以使用. queryselectorall()来选择所有td元素,然后使用. foreach()循环这些元素。它们的值可以用.innerHTML检索:

管理细胞=文档。 细胞. forEach(功能(细胞){ 控制台日志(细胞。innerHTML); }) <table . the 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 >

如果你只想从一个特定的行中选择列,你可以使用伪类:n -child()来选择一个特定的tr,可选地结合子组合子(>)(如果你有一个表中表):

const细胞=文档。 细胞. forEach(功能(细胞){ 控制台日志(细胞。innerHTML); }) <table . the 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 >

如果你想遍历每一行(<tr>),知道/识别行(<tr>),并遍历每行(<tr>)的每一列(<td>),那么这就是要走的路。

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
   }  
}

如果您只想遍历单元格(<td>),忽略您所在的行,那么可以这样做。

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
}

更好的解决方案:使用Javascript的原生array .from()并将HTMLCollection对象转换为数组,之后您可以使用标准的数组函数。

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.rowIndex和cell。而不是使用row_ind和col_ind。

我更喜欢这种方法,而不是前2个投票最多的答案,因为它不会让你的代码与全局变量I, j, row和col混淆,因此它提供了干净的,模块化的代码,不会有任何副作用(或提高lint /编译器警告)…没有其他库(例如jquery)。此外,它使您的代码可以访问元素和索引变量,而不仅仅是元素,如果您喜欢隐藏索引,您可以在回调参数列表中忽略它。

如果你需要在旧版本(es2015之前)的Javascript中运行,Array.from可以被填充。

我将其保留下来,以供将来参考,以便抓取特定的HTML表列并打印结果。

//select what table you want to scrape (is zero based)
//set 0 if there is only one
setTable=0;
//select what column you want to scrape (is zero based)
//in this case I would be scrapping column 2
setColumnToScrape=1;
var table = document.getElementsByTagName("tbody")[setTable];
for (var i = 0, row; row = table.rows[i]; i++) {
  col = row.cells[setColumnToScrape];
  document.write(col.innerHTML + "<br>");
}

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

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 = "";
     }
}