Search code examples
cypresscypress-cucumber-preprocessor

How to click on the next element using the first() and last() function in cypress?


In Cypress - The first() and last() functions in cypress picks or clicks on the first and last element inside the DOM. But what if I want to click the 2nd and the 3rd element.

Currently I am using below code to click on the first and last element :-

const fs = cy.get('div.outer-circle').first();
fs.click();

const ls = cy.get('div.outer-circle').last();
ls.click();

And I was trying to click on the second element. For which, I used next() functions also.

const ss = cy.get('div.outer-circle').next();
ss.click({multiple: true, force: true});

But unfortunately, it started clicking on all the elements.

Can anybody suggest here. How to go with this approach, I am pretty new to Cypress tool.


Solution

  • If you want to choose specific index you have to use .eq(docs). Example:

    cy.get('div.outer-circle').eq(4);
    

    The code above will return fourth element.

    PS. I would advise changing the way you store the elements. See https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous