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


190

如果我有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的每一行中的每个单元格中检索值?

Answers:


299

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

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

如果您只想浏览cells(<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
}

3
ex2,table.cells不兼容浏览器
EricG

7
@WilliamRemacle我在大约4年前发布了这个答案。当时IE 9甚至还没有想到!
John Hartsock 2014年

@JohnHartsock我知道,但我使用了您的解决方案,并发现它不适用于IE。只是警告他人而已。。。无论如何,我还是投票支持您的回答;-)
William Remacle 2014年

函数itTable(){document.writeln(“ itTable”); var table = document.getElementById(“ mytab”); for(var i = 0,row; row = table.rows [i]; i ++){document.writeln(i); for(var j = 0,col; col = row.cells [j]; j ++){document.writeln(j); }} document.writeln(“ end-itTable”); 这段代码为什么不能让我遍历一张与上面相似的表。
Doug Hauf 2014年

对于那些(需要通过Google来到这里)需要简单且小的填充程序table.cells(以修补一些较旧的/基于IE的代码)的人,请参阅对以下问题的
GitaarLAB 2014年

65

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

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

2
无法使用jquery ...公司不允许。不要问为什么。
GregH 2010年

21
那是一个疯狂的政策。您总是可以将所需的相关功能从jQuery复制并粘贴到自己的应用程序代码中。除非有禁止在线使用他人代码的政策,否则您就不会在这里。
克林顿

13
@朱迪:不同意“疯狂的政策”...。有很多不使用jQuery的理由
Bigjim 2014年

JQuery是我一段时间以来没有使用过的东西,乍一看似乎很复杂并且不易掌握。但是我认为那只是因为我没有太多使用它。
Doug Hauf 2014年

5
不允许JQuery的另一个原因是针对嵌入式网站,例如,我使用的嵌入式WiFi芯片整个网站只有250Kb。压缩所有图像。
尼克,

15

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
  }
}
<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循环停止(退出)时进行迭代。


在上一篇文章中:while(cell = row [r] .cells [c ++]应该是row.cells [c ++],row是当前对象,第s个示例代码:mycoldata = cell.innerHTML
fib Littul

12

尝试

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}


2
干净我会说
Shobi

3

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

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吗?因为您的for循环看起来有点像PHP。
aravk33

2
当您知道要查找的内容时,许多语言都惊人地相似。PHP将在每个变量前使用$,但并非如此。var也是JavaScript使用的关键字,不是PHP使用的关键字,尽管如果他们添加了它,我可能会错过它。-edit-不能输入换行符...正如我所说:逻辑是通用的。知道如何将其转录为其他语言是一项非常有用的技能,这并不难学习-我们是具有出色的模式匹配能力的智者。确定每种语言之间的更改,或仅使用词法分析器语言定义...
Acecool

3

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

    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#):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });

Uncaught TypeError:无法读取未定义的属性'toArray'->这是我在尝试此解决方案时得到的。
Vineela Thonupunuri

奇怪。我再试一次,它奏效了。但是,我无法重现您指出的错误。也许问题出在浏览器上。我使用Edge和IE进行了测试,但都无法正常工作。Chrome,Firefox和Safari正常运行。
l30_4l3X

我也用铬。
Vineela Thonupunuri

这也对我有用。该Object.defineProperty显然有代码的其余部分之前去,但它的工作原理。@Vineela Thonupunuri您是否以正确的顺序尝试了代码?
FlippingBinary

3

更好的解决方案:使用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.rowIndexcell.colIndex而不是使用row_indcol_ind

我更喜欢这种方法在上面2最高投票的答案,因为它不具有全局变量搞乱你的代码ijrowcol,因此它提供了清晰的,模块化的代码,不会有任何的副作用(或提高皮棉/编译器警告) ...没有其他库(例如jquery)。

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


1

您可以.querySelectorAll()用来选择所有td元素,然后使用来遍历这些元素.forEach()。可以使用以下方法检索其值.innerHTML

const cells = document.querySelectorAll('td');
cells.forEach(function(cell) {
  console.log(cell.innerHTML);
})
<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

使用单个for循环:

var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.