Home > Net >  Cypress, get the index of a specific element returned from cy.get()
Cypress, get the index of a specific element returned from cy.get()

Time:01-13

I'm writing Cypress tests for a website that has a series of quotations, some of which have a "Read More" button at the end, which displays the rest of the quote. If I use

cy.get(".quote")

it returns a list of several quotes. I can use

cy.get(".quote").find(".read-more").first()

to find the first quote that has a Read More button, but I want to know what the index of that element is in the original list of quotes. I'm testing to make sure that the Read More button correctly reveals the full quote, but the button disappears (entirely removed from the DOM, not just set to visibility: none) once it's been clicked, so I can't use the same command to find the quote again. If I could access the element of that quote, I could just use

cy.get(".quote").eq(element)

to pull out that specific quote again once the Read More button is gone.

CodePudding user response:

You can do something like this. Apply each over the quotes, then inside each search for the quote you are looking for and then get the index of that quote.

cy.get('.quote').each(($ele, index) => {
  if ($ele.text().includes('some part of the quote')) {
    cy.log(index) //logs the index
  }
})
  •  Tags:  
  • Related