W3cubDocs

/Cypress

parents

Get the parent DOM elements of a set of DOM elements.

Please note that .parents() travels multiple levels up the DOM tree as opposed to the .parent
()
command which travels a single level up the DOM tree.

The querying behavior of this command matches exactly how .parents() works in jQuery.

Syntax

.parents()
.parents(selector)
.parents(options)
.parents(selector, options)

Usage

Correct Usage

cy.get('aside').parents()  // Yield parents of aside

Incorrect Usage

cy.parents()              // Errors, cannot be chained off 'cy'
cy.go('back').parents()   // Errors, 'go' does not yield DOM element

Arguments

selector (String selector)

A selector used to filter matching DOM elements.

options (Object)

Pass in an options object to change the default behavior of .parents().

Option Default Description
log true Displays the command in the Command log
timeout defaultCommandTimeout Time to wait for .parents() to resolve before timing out

Yields

  • .parents() yields the new DOM element(s) it found.

Examples

No Args

Get the parents of the active li

<ul class='main-nav'>
  <li>Overview</li>
  <li>Getting started
    <ul class='sub-nav'>
      <li>Install</li>
      <li class='active'>Build</li>
      <li>Test</li>
    </ul>
  </li>
</ul>
// yields [.sub-nav, li, .main-nav]
cy.get('li.active').parents()

Selector

Get the parents with class main-nav of the active li

// yields [.main-nav]
cy.get('li.active').parents('.main-nav')

Rules

Requirements

  • .parents() requires being chained off a command that yields DOM element(s).

Assertions

  • .parents() will automatically retry until the element(s) exist in the DOM.

  • .parents() will automatically retry until assertions you've chained all pass.

Timeouts

  • .parents() can time out waiting for the element(s) to exist in the DOM.

  • .parents() can time out waiting for assertions you've added to pass.

Command Log

Get the parents of the active li

cy.get('li.active').parents()
Command Log parents

When clicking on the parents command within the command log, the console outputs the following:

Console Log parents

See also

© 2017 Cypress.io
Licensed under the MIT License.
https://docs.cypress.io/api/commands/parents.html