How to Get the First, or Nth Element in Cypress

How to Get the First, or Nth Element in Cypress

Ferenc Almasi β€’ 2021 September 30 β€’ Read time 1 min read
  • twitter
  • facebook

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();
example

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
example

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();
example

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to get the first element in Cypress?
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.