如何在 JavaScript 中遍历表格行和单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3065342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I iterate through table rows and cells in JavaScript?
提问by GregH
If I have an HTML table...say
如果我有一个 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>
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?
我将如何遍历所有表行(假设每次检查时行数都可能发生变化)并从 JavaScript 中的每一行中的每个单元格中检索值?
回答by John Hartsock
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.
如果你想遍历每一行(<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
}
}
If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.
如果您只想通过单元格(<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
}
回答by dzida
You can consider using jQuery. With jQuery it's super-easy and might look like this:
你可以考虑使用jQuery。使用 jQuery 非常简单,可能看起来像这样:
$('#mytab1 tr').each(function(){
$(this).find('td').each(function(){
//do your stuff, you can use $(this) to get current cell
})
})
回答by sbrbot
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>
In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).
在每次通过 while 循环 r/c 迭代器增加时,集合中的新行/单元格对象被分配给行/单元格变量。当集合中没有更多行/单元格时,将 false 分配给行/单元格变量并在循环停止(退出)时进行迭代。
回答by Kamil Kie?czewski
Try
尝试
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
let val = cell.innerText; // your code below
}
}
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.innerText)
}
}
<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>
for ( let [i,row] of [...mytab1.rows].entries() )
{
for( let [j,cell] of [...row.cells].entries() )
{
console.log(`[${i},${j}] = ${cell.innerText}`)
}
}
<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>
回答by l30_4l3X
If you want one with a functional style, like this:
如果你想要一个功能性的风格,像这样:
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"]
You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):
您可以修改 HTMLCollection 的原型对象(允许以类似于 C# 中的扩展方法的方式使用)并在其中嵌入一个将集合转换为数组的函数,允许使用具有上述样式的高阶函数(类似于 C# 中的 linq 样式) C#):
Object.defineProperty(HTMLCollection.prototype, "toArray", {
value: function toArray() {
return Array.prototype.slice.call(this, 0);
},
writable: true,
configurable: true
});
回答by mwag
Better solution: use Javascript's native Array.from()and to convert HTMLCollection object to an array, after which you can use standard array functions.
更好的解决方案:使用 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);
});
});
}
You could also reference tr.rowIndexand cell.colIndexinstead of using row_indand col_ind.
您也可以参考tr.rowIndexandcell.colIndex而不是使用row_indand col_ind。
I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i, j, rowand col, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery).
与前 2 个最高投票答案相比,我更喜欢这种方法,因为它不会使您的代码与全局变量i、j、row和col混淆,因此它提供了干净、模块化的代码,不会产生任何副作用(或引发 lint / 编译器警告) ...没有其他库(例如jquery)。
If you require this to run in an old version (pre-ES2015) of Javascript, Array.fromcan be polyfilled.
如果您需要它在旧版本(ES2015 之前)的 Javascript 中运行,则Array.from可以使用 polyfill。
回答by Karim O.
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 = "";
}
}
回答by Foram Shah
Using a single for loop:
使用单个 for 循环:
var table = document.getElementById('tableID');
var count = table.rows.length;
for(var i=0; i<count; i++) {
console.log(table.rows[i]);
}
回答by Obsidian Age
You can use .querySelectorAll()to select all tdelements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:
您可以使用.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>
If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child()to select a specific tr, optionally in conjunction with the child combinator (>)(which can be useful if you have a table within a table):
如果您只想从特定行中选择列,您可以使用伪类:nth-child()来选择特定的tr,可选择与子组合器 ( >)结合使用(如果您在表中有一个表,这可能很有用):
const cells = document.querySelectorAll('tr:nth-child(2) > 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>

