Search code examples
html-tablecypress

Find multiple elements of specific type


Given something like this:

<table>
 <tr id="row">
  <td>......</td>
  <td>......</td>
  <td>......</td>
 </tr>
 <tr id="row">
  ...

The tds have no id or other identificator.

How can I find, for instance, the third ?

I can find any <td> tag like this:

cy.get("td")

And I seem to be able to get a specific row like this:

cy.get("#row")[0]

But this does not work:

cy.get("#row")[0].cy.get("td")

What I want to do, is to be able to get the contents of, for instance, the third <td> in every row.


Solution

  • You can use cy.eq() to get an item from an array at a specific index.

    Get A DOM element at a specific index in an array of elements.

    So, given the example you provided:

    cy.get('td')
      .eq(2)
      ...
    // eq is index-0
    

    Additionally, Cypress provides .first() and .last as convenience functions to get the first and last item in the array, respectively. (No convenience functions for third though)

    If you need to find a specific row by an index, and then the specific td underneath it, the proper way would be to use .find() or another Cypress function to query only off of the yielded row.

    cy.get('#row')
      .eq(0) // or .first()
      .find('td')
      .eq(2)
      ...