How to Get Multiple Elements in Cypress

How to Get Multiple Elements in Cypress

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

In order to work on multiple in Cypress, we can use the built-in each command chained to a cy.get command in the following way:

Copied to clipboard! Playground
const labels = [
    'Features',
    'How it works',
    'Dashboard'
];

cy.get('ul li').each((item, index, list) => {
    // Returns the elements from the cy.get command
    expect(list).to.have.length(3);

    // Returns the current element from the loop
    expect(Cypress.$(item).text()).to.eq(labels[index]);
});

Note that it only works on array-like structures, so you only want to call it on multiple elements.

Let's say we want to work with the elements of a navigation menu. Here, we try to verify the list elements of an unordered list. The each command accepts three arguments in a callback function. These are in order:

  • item: 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

In the above code example, we verify the length of the list elements. Note that this will run the same expect three times. This could be rewritten to the following in order to execute the expect only once:

Copied to clipboard!
cy.get('ul li').should('have.length', 3);
example

Also, one thing to keep in mind: you need to wrap the current item with Cypress.$ in order to chain commands from it. 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 get multiple 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.