Access table’s row and cell using JavaScript
DOM Table provides additional links to simply navigation into it’s child like the navigation into the row and cells directly.
It useful to keep the code shorter and smarter.
A table references it’s rows and rows references it’s cells.
It means we can access the any row using the tables reference and we can access the any cell using the row reference.
Example:
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <table id="tbl" border="1"> <tr> <td>ONE</td> <td>TWO</td> <td>THREE</td> </tr> <tr> <td>FOUR</td> <td style="background-color:aqua">FIVE</td> <td>SIX</td> </tr> <tr> <td>SEVEN</td> <td>EIGHT</td> <td>NINE</td> </tr> </table> <script type="text/javascript"> var table = document.getElementById("tbl"); alert(tbl.rows[1].cells[1].innerHTML); // FIVE </script> </body> </html>
Access single cell (Click here to see live demo)
DOM table element has the rows and cells properties which is the array.
rows property has the collections of the all row of the table.
cells has the collections of the all cells of the specific row.
rows and cells property are the array so the always first element is located at the 0 (Zero) index and last element is located at the element.length – 1 index.
As you seen in above example, I am trying to access the second row and it’s second column, So I used the 1 as the index in both the rows and the cells property. So it will return the “FIVE”.
Example 1:
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <table id="tbl" border="1"> <tr> <td>ONE</td> <td>TWO</td> <td>THREE</td> </tr> <tr> <td>FOUR</td> <td>FIVE</td> <td>SIX</td> </tr> <tr> <td>SEVEN</td> <td>EIGHT</td> <td>NINE</td> </tr> </table> <script type="text/javascript"> var table = document.getElementById("tbl"); for (var i = 0 ; i < table.rows.length; i++) { var row = ""; for (var j = 0; j < table.rows[i].cells.length; j++) { row += table.rows[i].cells[j].innerHTML; row += " | "; } alert(row); } </script> </body> </html>
Access all rows and cells of the table (Click here to see live dmeo)
In above example, I am trying to the access the each and every cell of the table. So I used the loop on the rows property till the it’s length and also on the cells property till the it’s length so I can access the each any every cells of the table easily.