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);
}
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With