Cypress Difference between parent and parents command

Profile picture for user arilio666

Cypress Parent vs Parents

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 and return set of elements.

Example

Demo Link: http://autopract.com/selenium/list.html

Let us see a DOM level simple example to get a clear picture of how parent and parents work:

<ul class="nav-icon">
  <li>Origin</li>
  <li>Hello
    <ul class="nav-bar">
      <li>Install</li>
      <li class="active">Dream</li>
      <li>Night</li>
    </ul>
  </li>
</ul>

Parents Command

Let's say we want to get parents of class active.

cy.get('li.active').parents()
  • When we run this, we will get the parents of li.active
  • So here it will yield 3 elements
    1. ul.nav-bar
    2. li
    3. ul.nav-icon [or 5 if body and html exist]
  • We can use these selector yields to isolate and do operations within a specific parent-child DOM element.

Parent Command 

Let's say we want to get parent of class active.

cy.get('li.active').parent()
  • When we run this, we will get the immediate parent of li.active up to the DOM tree
  • So here it will yield ul.nav-var a single element as oppose to parents command.

You can get the specific element or elements using parent or parents command by giving selector as a parameter as well.

cy.get('li.active').parents('ul')
cy.get('li.active').parent('ul')

Here parents will return 2 elements [ul.nav-bar, ul.nav-icon] and parent will return 1, ul.nav-bar

So, these are the basic stuff needed to know about parent and parents where the parent is a command mainly used to fetch a single parent element of a child DOM element and Parents commands are used to fetch multiple parent elements of a child's DOM element.