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

前端 未结 9 1017
旧时难觅i
旧时难觅i 2020-11-22 13:05

If I have an HTML table...say

<
9条回答
  •  臣服心动
    2020-11-22 13:39

    Better solution: use Javascript's native Array.from() and to convert HTMLCollection object to an array, after which you can use standard array functions.

    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.rowIndex and cell.colIndex instead of using row_ind and 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, row and 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).

    If you require this to run in an old version (pre-ES2015) of Javascript, Array.from can be polyfilled.

提交回复
热议问题
col1 Val1