
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:
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.$
:
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:

Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: