How to select td of the table with JavaScript?

Sometimes, we want to select td of the table with JavaScript.

In this article, we’ll look at how to select td of the table with JavaScript.

How to select td of the table with JavaScript?

To select td of the table with JavaScript, we can use some DOM methods.

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')
const tds = table.querySelectorAll('td')
console.log(tds)

to select the table with querySelector.

Then we call table.querySelectorAll with 'td' to select all the td’s.

As a result, tds is a node list with the td elements.

Conclusion

To select td of the table with JavaScript, we can use some DOM methods.