Sometimes, we may want to iterate through HTML table rows and columns with JavaScript code.
In this article, we’ll look at how to iterate through table rows and cells with JavaScript.
Looping Through Tables and Rows and Cells with Plain JavaScript
We can loop through table rows and cells with plain JavaScript.
For instance, if we have the following HTML:
<table>
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
Then we can get a table’s rows by using the rows
property.
And to get the cells of each row, we can use the cells
property.
To do this, we write:
const table = document.querySelector("table");
for (const row of table.rows) {
for (const cell of row.cells) {
console.log(cell)
}
}
We get the table with document.querySelector
.
Then we use the for-of loop to loop through the table.rows
.
And then we use the row.cells
property to get the cells of each row.
To get the cell text, we can use the innerText
property:
const table = document.querySelector("table");
for (const row of table.rows) {
for (const cell of row.cells) {
console.log(cell.innerText)
}
}
Conclusion
We can loop through table rows and cells easily with native JavaScript properties.