I have a HTML table that contains both ROWSPANs and COLSPANs.
How can I find each cell\'s \"visual location\" using jQuery?
For example, here\'s a visual rep
your solution my proposed table design
+--+--+--+--+--+ +--+--+--+--+--+
| |A |B |C |D | | |A |B |C |D | length 5 vs 5
+--+--+--+--+--+ +--+--+--+--+--+
|1 |A1|B1 |D1| |1 |A1|B1|//|D1|
+--+--+--+--+ + +--+--+--+--+--+
|2 |A2 |C2| | |2 |A2|//|C2|//| length 3 vs 5
+--+ +--+ + +--+--+--+--+--+
|3 | |C3| | |3 |//|//|C3|//|
+--+--+--+--+--+ +--+--+--+--+--+
|4 |A4|B4|C4|D4| |4 |A4|B4|C4|D4|
+--+--+--+--+--+ +--+--+--+--+--+
|XYZ | |XY|//|//|//|//| length 1 vs 5
+--+--+--+--+--+ +--+--+--+--+--+
// cells labeled '//' above have this class
td.stuffing { display: none; }
Do you see what I did there?
This is the third row, for example:
2
A2
C2
Now the function to retrieve correct index is very simple.
function getCellLocation(cell) {
return {row:cell.parentNode.rowIndex, cell:cell.cellIndex}
}
function getSmartCell(table, row, col) {
var cell = table.rows[row].cells[col];
if (cell.className.indexOf("stuffing") == -1) return cell;
// traverse Left
while ((row>0) && (col>0) && (cell.className.indexOf("stuffing") >= 0)) {
cell = table.rows[row].cells[--col];
}
// roll back one cell if no colSpan is found
if (cell.colSpan == 1) cell = table.rows[row].cells[++col];
// traverse Up
while ((row>0) && (col>0) && (cell.className.indexOf("stuffing") >= 0)) {
cell = table.rows[--row].cells[col];
}
return cell;
}
Usage:
var tb = document.querySelector("table");
getCellLocation(getSmartCell(tb,3,2)); // {row: 2, cell: 1}
ATTENTION
I have just checked the code of getSmartCell and it returns wrong result if there are two neighbouring rowspans. I need to fix this.
Here is an example https://jsfiddle.net/goua3m13/