How to Get the First, or Nth Element in Cypress
To get the first element in Cypress from a list of DOM elements, we can use the first
command chained on cy.get
:
// Get the first li element
cy.get('ul li').first();
We also have the option to use eq
which accepts an index to use on an array of DOM elements. It's also possible to get the second element or any other elements with it in the following way:
cy.get('ul li').eq(0); // Get the first element
cy.get('ul li').eq(1); // Get the second element
cy.get('ul li').eq(2); // Get the third element
And so on. It works exactly like how jQuery's .eq()
function works. Likely, we also have the option to get the very last element using the last
command:
cy.get('ul li').last();
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: