Table Navigation in JS
Table navigation in JavaScript allows you to move through table elements (<table>, <tr>, <td>, etc.) dynamically. You can navigate rows, cells, and even specific elements inside a table.
Navigating Table Elements
The key DOM properties for table navigation are:
table.rows: Returns an HTMLCollection of all <tr> elements.
row.cells: Returns an HTMLCollection of all <td> or <th> elements in a row.
rowIndex: Returns the index of a row in the table.
cellIndex: Returns the index of a cell in its row.
nextElementSibling / previousElementSibling: Moves between rows or cells.
Example Table Structure
<table id="myTable" border="1">
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
Navigating Table Rows
Here's an example of how to navigate through table rows:
let table = document.getElementById("myTable");
let rows = table.rows;
for (let row of rows) {
console.log(row); // Logs each
}
Get a Specific Row by Index
let table = document.getElementById("myTable");
let rows = table.rows;
for (let row of rows) {
console.log(row); // Logs each
}
Navigating Table Cells
Here's an example of how to navigate through table cells:
let firstRow = table.rows[0];
let cells = firstRow.cells;
for (let cell of cells) {
console.log(cell.innerText); // Logs each cell's text
}
Get a Specific Row by Index
let specificCell = table.rows[1].cells[1]; // Second row, second cell
console.log(specificCell.innerText);