We use find() to look for elements inside a specific parent element. This helps us focus on a smaller part of the page and avoid mistakes.
0
0
cy.find() within parent in Cypress
Introduction
When you want to check a button inside a specific form, not the whole page.
When multiple sections have similar elements and you want to test only one section.
When you want to be sure you are clicking a link inside a certain container.
When you want to get text from a child element inside a parent container.
When you want to avoid selecting elements outside a specific part of the page.
Syntax
Cypress
cy.get('parentSelector').find('childSelector')
cy.get() finds the parent element first.
find() looks only inside that parent for the child element.
Examples
This finds the button with class
submit inside the element with ID login-form.Cypress
cy.get('#login-form').find('button.submit')
This checks that inside the element with class
menu, there are 5 links (a tags).Cypress
cy.get('.menu').find('a').should('have.length', 5)
This finds all
h2 headings inside section elements and checks if any contain the text 'Welcome'.Cypress
cy.get('section').find('h2').contains('Welcome')
Sample Program
This test visits a page, finds the form with class action-form, then finds a button inside it and checks if the button text says 'Submit'.
Cypress
describe('Test cy.find() within parent', () => { it('finds a button inside a form', () => { cy.visit('https://example.cypress.io/commands/actions') cy.get('.action-form').find('button').should('contain.text', 'Submit') }) })
OutputSuccess
Important Notes
Always use cy.get() first to select the parent before using find().
find() only searches inside the parent element, making tests more precise.
If find() does not find the element, the test will fail.
Summary
find() helps you look inside a parent element.
It makes your tests clearer and safer by focusing on a smaller part of the page.
Use it when you want to find child elements inside a specific container.