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

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

If I have an HTML table...say

<
9条回答
  •  情话喂你
    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
        });
    

提交回复
热议问题
col1 Val1