Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you select a table cell by its index?

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]
like image 558
kirgy Avatar asked Jun 07 '12 22:06

kirgy


People also ask

What is data cell index in Javascript?

The cellIndex property returns the position of a cell in the cells collection of a table row.

How do I find row and column index?

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).


2 Answers

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];
like image 159
Paul Avatar answered Oct 23 '22 17:10

Paul


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
like image 21
nnnnnn Avatar answered Oct 23 '22 17:10

nnnnnn