Chaining selectors helps you find elements inside other elements easily. It makes tests clear and simple.
0
0
Chaining selectors in Cypress
Introduction
When you want to find a button inside a specific form.
When you need to check a list item inside a certain list.
When you want to click a link inside a navigation bar.
When you want to verify text inside a specific section.
When you want to avoid selecting wrong elements with similar names.
Syntax
Cypress
cy.get('parentSelector').find('childSelector')
cy.get() finds the parent element first.
.find() looks inside the parent for the child element.
Examples
Finds the text input inside the form with id 'login'.
Cypress
cy.get('form#login').find('input[type="text"]')
Finds the active list item inside the menu list.
Cypress
cy.get('ul.menu').find('li.active')
Checks that the navigation bar has 5 links inside.
Cypress
cy.get('nav').find('a').should('have.length', 5)
Finds the first paragraph inside the content section and checks its text.
Cypress
cy.get('section.content').find('p').first().should('contain', 'Welcome')
Sample Program
This test visits a page, finds the search form, then finds and clicks the submit button inside it. Finally, it checks the URL changed to include 'search'.
Cypress
describe('Chaining selectors example', () => { it('Finds and clicks a button inside a form', () => { cy.visit('https://example.cypress.io') cy.get('form#search').find('button[type="submit"]').click() cy.url().should('include', 'search') }) })
OutputSuccess
Important Notes
Chaining selectors improves test accuracy by narrowing down elements.
It reduces flakiness by avoiding selecting wrong elements with similar classes or tags.
Use chaining instead of long complex selectors for better readability.
Summary
Chaining selectors means finding a parent element first, then searching inside it.
This helps target elements precisely and write clearer tests.
Use cy.get() followed by .find() to chain selectors in Cypress.