How to get the total number of Rows in a table | Cypress

Viewed 6715
  1. I have a table with N rows. How can I get the total number of rows present in the table?
  2. I search for a name, and that particular name is in row number X, how can I get the value of that particular row.
1 Answers

You can use .find to solve both of your cases.

To get the table row count:

  cy.get("#tableID")
    .find("tr")
    .then((row) => {
      //row.length will give you the row count
      cy.log(row.length);
    });

To get the value ( index ) of the particular row, you can do something like this.

  cy.get("#Table Id")
    .find("tr")
    .then((rows) => {
      rows.toArray().forEach((element) => {
        if (element.innerHTML.includes("Your Value")) {
        //rows.index(element) will give you the row index
          cy.log(rows.index(element));
        }
      });
    });

Additional tip: If you want to select a specific table cell containing a value, you can do this:

  cy.get("#customers").find("tr").find("td").contains("Germany");

Note: to get the table row index there can be many other alternative ways. Hope you will figure them out on the go.

Related