skip to Main Content

I get the following code which runs a loop through all children. I need to get the number of iterations in order to compare it with total number of children. That’s needed to click on Next button once the loop is on its last iteration so the new page will open.

 cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').each(
      ($element, index) => {
        cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').then(
          (listing) => {
            const listingCount = Cypress.$(listing).length;
            cy.log('Number of elements: ' + listingCount);
          }
    );
    if (listingCount !=== index-1) {
    // Do some magic here if it's not the last iteration
       } 
  });

I am not sure if this solution is right and don’t invoke any problems using the same locator twice. Is there any approach to get the number of found elements just declaring the loop, to avoid using this?

cy.get('[data-automation="AssetGrids_GridItemContainer_div"]').then(
          (listing) => {
            const listingCount = Cypress.$(listing).length;
            cy.log('Number of elements: ' + listingCount);
          }

2

Answers


  1. cy.each() can also yield you the original collection that you are iterating through. You can use the size of the collection to compare it to the current index, without needing to use Cypress to re-get() the element.

    cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
      .each((value, index, collection) => {
        if (index + 1 < collection.length) {
          // code to run if not the last iteration
        } else {
          // code to run if the last iteration
        }
      });
    
    Login or Signup to reply.
  2. Take a look at Help with JQuery selector :not(:last).

    Using the :not(:last) selector in a .filter() will change the list passed to .each().

    cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
      .filter(':not(:last)')
      .each(($element) => {   // the last element is excluded
        ...
      })
    

    If you want an else section, :last-child can be used inside the loop

    cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
      .each(($element) => {  
        if ($element.is(':last-child')) {
    
        } else {
    
        }
      })
    

    And :nth-child(index) can be used for an arbitrary position (note index is 1-based not 0-based).

    cy.get('[data-automation="AssetGrids_GridItemContainer_div"]')
      .each(($element) => {  
        if ($element.is(':nth-child(2)')) {   // 2nd item
    
        } else {
    
        }
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search