LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】TABLEのテキストを二次元配列で取得(結合セル対応)リベンジ

Last updated at Posted at 2021-06-18

概要

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 result = [];
    const rows = table.rows;
    let y = rows.length;
    while (--y > -1) {  //各行のループ
        const rowResult = [];
        const cells = rows[y].cells;
        const m = cells.length;
        let colSum = 0; //各行のcolspan合計
        let x = -1;
        while (++x < m) {   //行内セルのループ
            const cell = cells[x]
            const text = cell.textContent;
            const cs = cell.colSpan;
            let rs = cell.rowSpan - 1;
            if (cs===1) {
                rowResult.push(text);
                //結合セル[縦]対応
                while (--rs > -1) result[rs].splice(colSum, 0, text);
            } else {    //結合セル[横]対応
                const multi = Array(cs).fill(text);
                rowResult.push(...multi);
                //結合セル[縦]対応
                while (--rs > -1) result[rs].splice(colSum, 0, ...multi);
            }
            colSum += cs;
        }
        result.unshift(rowResult);
    }
    return result;
};

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

0
0
2

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
0
0