Categories
JavaScript Answers

How to Get the Row Count of an HTML Table with JavaScript?

Spread the love

To get the row count of an HTML table with JavaScript, we can use the rows.length property to get the total number of rows in the table.

And to get the number of rows in tbody , we can use the tBodies[0].rows.length property.

For instance, if we have the following table:

<table>
  <thead>
    <tr>
      <th>Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1</td>
    </tr>
    <tr>
      <td>Row 2</td>
    </tr>
    <tr>
      <td>Row 3</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Footer</td>
    </tr>
  </tfoot>
</table>

We can write:

const table = document.querySelector("table");
const totalRowCount = table.rows.length;
const tbodyRowCount = table.tBodies[0].rows.length;
console.log(totalRowCount, tbodyRowCount)

to get the total number of rows with table.rows.length where table is the table selected with document.querySelector .

And to get the number of rows in tbody , we write:

table.tBodies[0].rows.length

Therefore totalRowCount is 5 and tbodyRowCount is 3.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *