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
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.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()
.If you want an
else
section,:last-child
can be used inside the loopAnd
:nth-child(index)
can be used for an arbitrary position (note index is 1-based not 0-based).