How do you select a table cell by its index?
html, javascript
Solution
To access a cell by its row index and cell index within that row you can use:
var rowIndex = 0;
var cellIndex = 1;
document.getElementById('table1').rows[rowIndex].cells[cellIndex];
This will access the second cell (index 1) in your first row (index 0)
If you want to just use cell index (and not keep track of rows) and have it iterate through the cells in each row, you can do this, but only if every row has the same number of cells. The following code would access the fourth cell in the table (index 3) whether it's in row 0, 1, or 3; as long as each row has the same number of cells:
var cellIndex = 3;
var table = document.getElementById('table1');
var num_columns = table.rows[0].cells.length;
var cell = table.rows[Math.floor(cellIndex/num_columns)].cells[cellIndex % num_columns];
Problem
I know there is a way of accessing sequential elements, but I'm not sure how to access them by index. Is there a way to do it? I'm looking for something like: ``` document.getElementById('table1').cell[1] ```