How do you select a table cell by its index?

I know there is a way to access sequential elements, but I'm not sure how to access them by index. Is there any way to do this?

I am looking for something like:

document.getElementById('table1').cell[1] 
+6
source share
5 answers

To access a cell by row index and cell index inside 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 the cell index (and not track the rows) and pass it through the cells in each row, you can do this, but only if each row has the same number of cells. The following code will gain access to the fourth cell in the table (index 3), whether on line 0, 1, or 3; while 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]; 
+15
source

The .rows collection table provides row access. String collection .cells provides access to these row cells. Both use zero-indexing and have the .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 
+4
source

To limit the query by id to the item tree, you can use querySelector :

 document.getElementById('table1').querySelector('#cell1'); 

But it's just superfluous when you can just do

 document.getElementById('cell1'); 

Change To better respond to an OP query, you can access the table cells sequentially as follows:

 document.getElementById('table1').tBodies[i].rows[j].cells[k]; 

Here, the k cell of the j row of the i th table body is selected. If your table has only one <tbody> element (for example, a regular one) or you want to access the cells separately from their <tbody> , you can omit the .tBodies[i] .

+2
source
 document.querySelector('table td'); //Done. IE8 and above supported. //Only the first one will be selected. 

 document.querySelector('#table1 td'); //First cell in #table1 document.querySelector('#table1 td:nth-child(3)'); //Third cell in #table1 document.querySelectorAll('#table1 td')[2]; //or this 
+2
source

Give cell <td> identifier:

 <td id="mycell"> 

Then you can access the DOM object with getElementById() :

 document.getElementById('mycell'); 
0
source

Source: https://habr.com/ru/post/917568/


All Articles