0
0
Cypresstesting~5 mins

Parent commands in Cypress

Choose your learning style9 modes available
Introduction

Parent commands help you find the parent element of a selected element on a web page. This is useful to check or interact with the container or group that holds the element.

When you want to check the style or attribute of a container around a button or link.
When you need to find a form or section that holds a specific input field.
When you want to click or verify something on the parent element of a selected item.
When you want to make sure the parent element has certain text or class.
When you want to chain commands starting from a child element to its parent.
Syntax
Cypress
cy.get('child-selector').parent([selector])

The parent() command gets the direct parent of the element found by get().

You can optionally pass a selector to filter the parent element.

Examples
Finds the button element, then gets its direct parent element.
Cypress
cy.get('button').parent()
Finds elements with class item, then gets their parent only if it has class container.
Cypress
cy.get('.item').parent('.container')
Finds the element with id input1, then gets its direct parent element.
Cypress
cy.get('#input1').parent()
Sample Program

This test visits a sample page, finds a button with class traversal-button, then checks if its parent has the class btn-group.

Cypress
describe('Parent command example', () => {
  it('checks parent element class', () => {
    cy.visit('https://example.cypress.io/commands/traversal')
    cy.get('.traversal-button').parent().should('have.class', 'btn-group')
  })
})
OutputSuccess
Important Notes

The parent() command only gets the direct parent, not ancestors higher up.

If no parent matches the optional selector, the command will fail.

Use parents() if you want to get all ancestors instead of just the direct parent.

Summary

Parent commands help find the direct parent of an element.

You can check or interact with the parent element easily.

Use optional selectors to filter the parent element.