Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  51] [ 6]  / answers: 1 / hits: 47922  / 12 Years ago, thu, june 7, 2012, 12:00:00

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]

More From » html

 Answers
20

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];

[#85070] Thursday, June 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;