Skip to main content

prev

Get the immediately preceding sibling of each element in a set of the elements.

info

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

Syntax

.prev()
.prev(selector)
.prev(options)
.prev(selector, options)

Usage

Correct Usage

cy.get('tr.highlight').prev() // Yield previous 'tr'

Incorrect Usage

cy.prev() // Errors, cannot be chained off 'cy'
cy.getCookies().prev() // Errors, 'getCookies' 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 .prev().

OptionDefaultDescription
logtrueDisplays the command in the Command log
timeoutdefaultCommandTimeoutTime to wait for .prev() to resolve before timing out

Yields

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

Examples

No Args

Find the previous element of the element with class of active

<ul>
<li>Cockatiels</li>
<li>Lorikeets</li>
<li class="active">Cockatoos</li>
<li>Conures</li>
<li>Eclectus</li>
</ul>
// yields <li>Lorikeets</li>
cy.get('.active').prev()

Selector

Find the previous element with a class of active

<ul>
<li>Cockatiels</li>
<li>Lorikeets</li>
<li class="active">Cockatoos</li>
<li>Conures</li>
<li>Eclectus</li>
</ul>
// yields <li>Cockatoos</li>
cy.get('li').prev('.active')

Rules

Requirements

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

Assertions

  • `.prev()` will automatically [retry](/guides/core-concepts/retry-ability) until the element(s) [exist in the DOM](/guides/core-concepts/introduction-to-cypress#Default-Assertions)
  • `.prev()` will automatically [retry](/guides/core-concepts/retry-ability) until all chained assertions have passed

Timeouts

  • `.prev()` can time out waiting for the element(s) to [exist in the DOM](/guides/core-concepts/introduction-to-cypress#Default-Assertions).
  • `.prev()` can time out waiting for assertions you've added to pass.

Command Log

Find the previous element of the active li

cy.get('.left-nav').find('li.active').prev()

The commands above will display in the Command Log as:

Command Log prev

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

Console Log prev

See also