JavascriptでcolSpanやrowSpanが含まれたテーブルの特定のセルの相対的なインデクス(cellIndex)を調べる




function cellsIndex (table = document.querySelector ('table')) {
  let
    rows = table.tHead ? table.tHead.rows: [table.rows[0]],//tHeadの全てor tBodyの最初の行
    rst = new Map,
    buf = [ ];

  if (! rows.length)
    throw new Error ();

  //すべてのセルを走査する
  for (let row of rows) {
    for (let cell of row.cells) {
      let x = 0;
      //第1行目の配列から最初のfalseの番号を代入
      for (let a of buf[0] || [])
        if (a) x++; else break;
      rst.set (cell, x);//Mapに登録

      //colspan, rowspan から buf での範囲を塗りつぶす
      let
        W = x + cell.colSpan,
        H = cell.rowSpan;

      for (let h = 0; h < H; h++) {
        if ('undefined' === typeof buf[h])
          buf[h] = [ ];//bufの配列を追加するか
        for (let w = x, b = buf[h]; w < W; w++)
          b[w] = true;
      }
    }
    buf.shift ();//次行に移行の為削除
  }
  return rst;
}
  

//以下実行サンプル
const TH = cellsIndex ();

document.addEventListener ('click', (event)=> {
  let th = event.target.closest ('th');
  if (TH.has (th))
    alert ("cell offset index: " + TH.get (th));
}, false);