Skip to content

Instantly share code, notes, and snippets.

@nikitaeverywhere
Last active October 15, 2019 18:59
Show Gist options
  • Save nikitaeverywhere/a96c8e7f8c0fe4e16a31 to your computer and use it in GitHub Desktop.
Save nikitaeverywhere/a96c8e7f8c0fe4e16a31 to your computer and use it in GitHub Desktop.
JavaScript function that returns the cell of the table by given coordinates considering colSpan and rowSpan of the cells.
/**
* Returns the cell of the table by given (x;y) coordinates considering colSpan and rowSpan of the cells.
* @param {HTMLElement} table - HTML table
* @param {number} x - X position in table matrix
* @param {number} y - Y position in table matrix
* @returns {HTMLElement|null}
*/
var getTableCell = function (table, x, y) {
var m = [], row, cell, xx, tx, ty, xxx, yyy;
for(yyy = 0; yyy < table.rows.length; yyy++) {
row = table.rows[yyy];
for(xxx = 0; xxx < row.cells.length; xxx++) {
cell = row.cells[xxx];
xx = xxx;
for(; m[yyy] && m[yyy][xx]; ++xx) {}
for(tx = xx; tx < xx + cell.colSpan; ++tx) {
for(ty = yyy; ty < yyy + cell.rowSpan; ++ty) {
if (!m[ty])
m[ty] = [];
m[ty][tx] = true;
}
}
if (xx <= x && x < xx + cell.colSpan && yyy <= y && y < yyy + cell.rowSpan)
return cell;
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment