How to iterate through a table rows and get the cell values using JavaScript?

Sometimes, we want to iterate through a table rows and get the cell values using JavaScript.

In this article, we’ll look at how to iterate through a table rows and get the cell values using JavaScript.

How to iterate through a table rows and get the cell values using JavaScript?

To iterate through a table rows and get the cell values using JavaScript, we can use the row property.

For instance, we write:

<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>A2</td>
      <td>A3</td>
    </tr>
    <tr>
      <td>B1</td>
      <td>B2</td>
      <td>B3</td>
    </tr>
    <tr>
      <td>C1</td>
      <td>C2</td>
      <td>C3</td>
    </tr>
  </tbody>
</table>

to add a table.

Then we write:

const table = document.querySelector('table')
for (const r of table.rows) {
  for (const c of r.cells) {
    console.log(c.innerHTML)
  }
}

to select the table with querySelector.

Then we loop through the table.rows property which is an object with the tr elements.

Then we loop through the cells which has the th and td elements.

And then we get the innerHTML value to get its contents.

Conclusion

To iterate through a table rows and get the cell values using JavaScript, we can use the row property.