javascriptlistseleniumcypressqwebelement

Cypress How can I get the same-named element count


in selenium I just creating web element list to learn that, in cypress I use .each() method to iterate in same-named elements but Some times I just need to know the same-named elements number to use this number somewhere else.

How can I do that in cypress?


Solution

  • You can store the length of the yielded list of elements via an alias.

    cy.get('foo')
      .its('length')
      .as('listLength');
    ... // later
    cy.get('@listLength').should('be.gte', 1);
    

    If you need to access the variable value synchronously, you could store it in a Cypress environment variable, or a regular JS variable.

    let lengthVar;
    cy.get('foo')
      .its('length')
      .then((length) => {
        // If storing in a Cypress.env() variable
        Cypress.env('listLength', length);
        // If storing in a traditional JS variable
        lengthVar = length;
      });