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
:
Copied to clipboard!
// 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:
Copied to clipboard!
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:
Copied to clipboard!
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:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews