These commands help you pick specific elements from a group on a web page. It makes testing easier by focusing on one item.
0
0
cy.first(), cy.last(), cy.eq() in Cypress
Introduction
When you want to test the very first item in a list or menu.
When you need to check the last button in a group of buttons.
When you want to select a specific item by its position in a list.
When you want to make sure a certain element among many behaves correctly.
When you want to avoid testing all elements and focus on one for faster tests.
Syntax
Cypress
cy.get('selector').first() cy.get('selector').last() cy.get('selector').eq(index)
cy.get('selector') finds all elements matching the selector.
first() picks the first element, last() picks the last, and eq(index) picks the element at the given zero-based index.
Examples
Selects the first list item inside an unordered list.
Cypress
cy.get('ul li').first()
Selects the last button on the page.
Cypress
cy.get('button').last()
Selects the third element with class 'item' (index starts at 0).
Cypress
cy.get('.item').eq(2)
Sample Program
This test visits a sample page with buttons. It checks the first button's text, confirms the last button is visible, and verifies the third button has a specific class.
Cypress
describe('Test first, last, and eq commands', () => { beforeEach(() => { cy.visit('https://example.cypress.io/commands/actions') }) it('checks first, last, and eq elements', () => { // Check first button text cy.get('.action-btn').first().should('have.text', 'Button') // Check last button is visible cy.get('.action-btn').last().should('be.visible') // Check third button has correct class cy.get('.action-btn').eq(2).should('have.class', 'btn-primary') }) })
OutputSuccess
Important Notes
Index in eq() starts at 0, so eq(0) is the first element.
Use these commands after cy.get() to narrow down elements.
These commands help keep tests simple and focused on one element.
Summary
first() selects the first element from a group.
last() selects the last element from a group.
eq(index) selects the element at the given position (starting at 0).