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

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

If I have an HTML table...say

<
相关标签:
9条回答
  • 2020-11-22 13:35

    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>

    0 讨论(0)
  • 2020-11-22 13:36

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

        Object.defineProperty(HTMLCollection.prototype, "toArray", {
            value: function toArray() {
                return Array.prototype.slice.call(this, 0);
            },
            writable: true,
            configurable: true
        });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题
col1 Val1