How to Iterate Over Elements and Work with Indexes in Cypress
To iterate over elements in Cypress and get their indexes, you want to use the each
command, which accepts a callback function with three different arguments, including the index as well:
Copied to clipboard! Playground
cy.get('menu li').each((element, index, list) => {
// Returns the current li element
expect(Cypress.$(element)).to.be.visible;
// Returns the index of the loop
expect(index).to.be.greaterThan(-1);
// Returns the elements from the cy.get command
expect(list).to.have.length(3);
});
In order, these are:
element
: The current (in this caseli
) element in the listindex
: The index of the looplist
: The element itself that has been selected withcy.get
, in this case, an array ofli
Note that in order to use Cypress commands on the element
, you need to wrap it with cy.wrap
. Or if you need to use jQuery functions on it, then you can use Cypress.$
:
Copied to clipboard!
cy.wrap(element).click(); // wrap element with Cypress
Cypress.$(element).text(); // wrap element with jQuery
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews