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]
The cellIndex property returns the position of a cell in the cells collection of a table row.
For example, if we have a data frame called df that contains a value say Data then we can find the row and column index of Data by using the command as which(df=="Data",arr. ind=TRUE).
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];
A table's .rows
collection provides access to the rows. A row's .cells
collection provides access to that row's cells. Both use zero-based indexing and have a .length
property. So:
var table = document.getElementById('table1');
alert(table.rows.length); // number of rows
alert(table.rows[2].cells.length); // number of cells in row 3
alert(table.rows[2].cells[5].innerHTML); // contents of 6th cell in 3rd row
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With