Cypress parent command

Profile picture for user devraj

Cypress parent command gets the parent DOM element of a set of DOM elements. parent() command is different from parents() command, parent() only travels a single level up the DOM tree as opposed to the parents() command which travels multiple levels.

The querying behavior of parent() command is exactly same as JQuery .parent() method which returns the direct parent element of the selected element. 

Syntax

This command has 4 variations

.parent()
.parent(selector)
.parent(options)
.parent(selector, options)

Here in options we can use log and timeout.

Note: This command can not be chained with cy object so you can not type cy.parent()

When you will use parent command after selecting the child element, it will yield the new DOM element. After getting the element you can assert that parent should have some class or attribute or anything else. Also, you can perform some action on parent element. You can chain parent() with another parent() command, children()  command or any other command.

Example

For demo we will consider autopract website where we will perform following 3 actions:

  1. Assert parent contain particular attribute
  2. refer parent of parent and check it contains particular class
  3. refer sibling of an element using parent and child command
  it.only('find get difference', ()=> {

    cy.visit("/")
    cy.get('button.close').click();
    
    // Assert parent attribute
    cy.get('li.mobile-setting').parent().should('have.attr','_ngcontent-serverapp-c68')

    // refer parent of parent
    cy.get('li.mobile-setting').parent().parent().should('have.class','icon-nav')

    // Click on sibling element using parent and children
    cy.get('li.mobile-setting').parent().children('#search-widgets').click()
  })