These commands help you find related elements on a webpage. cy.parent() finds the parent of an element, and cy.children() finds all direct children of an element.
cy.parent() and cy.children() in Cypress
cy.get('selector').parent() cy.get('selector').children()
cy.parent() returns the immediate parent element of the matched element.
cy.children() returns all direct child elements of the matched element.
cy.get('button').parent()
li) inside the ul list.cy.get('ul').children()
item has the class container.cy.get('.item').parent().should('have.class', 'container')
menu has exactly 5 direct children.cy.get('#menu').children().should('have.length', 5)
This test visits a sample page. The first test finds an element with class traversal-badge and checks if its parent has class traversal-button. The second test checks that the element with class traversal-list has exactly 5 children.
describe('Test cy.parent() and cy.children()', () => { beforeEach(() => { cy.visit('https://example.cypress.io/commands/traversal') }) it('checks parent element', () => { cy.get('.traversal-badge').parent().should('have.class', 'traversal-button') }) it('checks children elements count', () => { cy.get('.traversal-list').children().should('have.length', 5) }) })
Always use specific selectors to avoid selecting wrong elements.
cy.parent() only goes one level up. To go higher, chain multiple parent() calls.
cy.children() only returns direct children, not deeper descendants.
cy.parent() finds the immediate parent of an element.
cy.children() finds all direct children of an element.
Use these commands to navigate and test the page structure easily.