0
0
Cypresstesting~5 mins

cy.parent() and cy.children() in Cypress

Choose your learning style9 modes available
Introduction

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.

When you want to check the container of a button or link.
When you need to verify all items inside a list or menu.
When you want to move from a child element to its parent to check styles or attributes.
When you want to test if a parent element contains the correct children.
When you want to chain commands to navigate the page structure easily.
Syntax
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.

Examples
This finds the parent element of the first button found on the page.
Cypress
cy.get('button').parent()
This finds all direct child elements (usually li) inside the ul list.
Cypress
cy.get('ul').children()
This checks if the parent of an element with class item has the class container.
Cypress
cy.get('.item').parent().should('have.class', 'container')
This verifies that the element with id menu has exactly 5 direct children.
Cypress
cy.get('#menu').children().should('have.length', 5)
Sample Program

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.

Cypress
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)
  })
})
OutputSuccess
Important Notes

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.

Summary

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.