How to Iterate Over Elements and Work with Indexes in Cypress

How to Iterate Over Elements and Work with Indexes in Cypress

Ferenc Almasi β€’ 2021 September 30 β€’ Read time 1 min read
  • twitter
  • facebook

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 case li) element in the list
  • index: The index of the loop
  • list: The element itself that has been selected with cy.get, in this case, an array of li

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:

Learn Cypress with Educative
How to iterate over elements in Cypress?
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.