Breaking out `.each` loop in `Cypress`

Viewed 7249

I have the following code

let c = 0
cy.get(selector).each(count => {
   if (++c == count-1)
      break
   //somthing 
})

Let's say we have n selected DOM objects, and I want to apply some function on only n-2 objects. Is it possible to do it in Cypress?

2 Answers

As described in the documentation here, you can just do return false; if the condition which should stop the loop is triggered.

let c = 0
cy.get(selector).each(count => {
   if (++c == count-1) return false;
   // loop execution code
})

showcase - max (count) equals 2.

let count = 0;
const max = 2;

cy.get(selector).each((element) => {

if (count == max) return false;

cy.wrap(element).click();

count++;
}
Related