Get the row/column index of a table cell

It is surprising and annoying there is no easy way in html to get the accurate table row/column index of a cell if the table uses rowspan or colspan. This code does not reimplement the entire html spec’s algorithm because it is digusting but should work in all reasonable scenarios and the most common unreasonable scenarios:

https://jsfiddle.net/yjxt8jpg/1/

checkCellIndex = function(event) {

  var cell = event.target;

  var table = event.currentTarget;

 

  var grid = [];

  for(var i = 0; i < table.rows.length; i++) {

    var currentRow = table.rows[i];

    var currentGridRow = grid[i] || (grid[i] = []);

    for(var j = 0; j < currentRow.cells.length; j++) {

      var currentCell = currentRow.cells[j];

      var c = 0; while(currentGridRow[c]) { c++; }

      for(var cx = 0; cx < Math.max(1,currentCell.colSpan|0); cx++) {

        for(var rx = 0; rx < Math.max(1,currentCell.rowSpan|0); rx++) {

          var gridRowToUpdate = grid[i+rx] || (grid[i+rx] = []);

          gridRowToUpdate[c+cx] = gridRowToUpdate[c+cx] || currentCell;

        }

      }

    }

  }

 

  //alert(grid.map(row => JSON.stringify(row.map(cell => cell ? cell.textContent : ''))).join('\n'));

  for(var rx = 0; rx < grid.length; rx++) {

    for(var cx = 0; cx < grid[rx].length; cx++) {

      if(grid[rx][cx] == cell) {

        alert((1+rx)+'x'+(1+cx));

        rx = grid.length;

        break;

      }

    }

  }

 

}

Published on 2016-12-29 under ALL, HTML, JS, WEB

Comments

A javascript file is loading the comments.