LoginSignup
1
1

More than 3 years have passed since last update.

【javascript】TABLEセル内のテキストデータを二次元配列で全取得(colspan/rowspan対応)

Last updated at Posted at 2020-09-19

何かあればご指摘いただけると助かります。

概要

head1 head2 haed3 head4 head5
1-1 1-2 1-3 1-4 1-5
2-1 2-2 2-3 2-4 2-5
3-1 3-2 3-3 3-4 3-5

こんな感じのテーブルを

[
    ['head1','head2', 'haed3', 'head4', 'head5'],
    ['1-1', '1-2', '1-3', '1-4', '1-5'],
    ['2-1', '2-2', '2-3', '2-4', '2-5'],
    ['3-1', '3-2', '3-3', '3-4', '3-5']
]

二次元配列として取得します。
結合されたセルに対しては、結合元と同じテキストで埋めます。

コード

const getTableTexts = table => {
    const tableTexts = [];

    const tableRows = table.rows;
    //行数
    const numOfRows = tableRows.length;
    //列数(1行目参照)
    const numOfCols = [...tableRows[0].cells].reduce( (n, cell) => n + (cell.colSpan-0), 0);

    //rowspan管理用
    const rowspans = Array(numOfCols).fill(0);

    const getLineTexts = lineIdx => {
        const lineTexts = [];

        //colspan分の穴埋め + 行を配列で取得[rowspan, text-data]
        const dataOfLine = [...tableRows[lineIdx].cells].flatMap( cell => 
            Array(cell.colSpan-0).fill([cell.rowSpan-1, cell.textContent]) );

        let dataIdx = 0;    //dataOfLine用のindex
        for (let i=0; i<numOfCols; i++) {   //列ループ
            if (rowspans[i]) {  //数値が1以上:rowspan範囲内なので一行上のデータで穴埋め
                rowspans[i]--;
                lineTexts.push(tableTexts[lineIdx-1][i]);
            } else {    //0の時:rowspan範囲外なのでdataOfLineのデータを挿入
                const [num, text] = dataOfLine[dataIdx];
                if (num) rowspans[i] += num;
                lineTexts.push(text);
                dataIdx++;
            }
        }
        tableTexts.push(lineTexts);
    };
    //行ループ
    for (let i=0; i<numOfRows; i++) getLineTexts(i);

    return tableTexts;
};

const tableTexts = getTableTexts(document.getElementsByTagName('table')[0]);
console.table(tableTexts);

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1