Skip to main content

closest

Get the first DOM element that matches the selector (whether it be itself or one of its ancestors).

info

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

Syntax

.closest(selector)
.closest(selector, options)

Usage

Correct Usage

cy.get('td').closest('.filled') // Yield closest el with class '.filled'

Incorrect Usage

cy.closest('.active') // Errors, cannot be chained off 'cy'
cy.clock().closest() // Errors, 'clock' does not yield DOM elements

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 .closest().

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

Yields

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

Examples

Selector

Find the closest element of the .error with the class 'banner'

cy.get('p.error').closest('.banner')

Rules

Requirements

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

Assertions

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

Timeouts

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

Command Log

Find the closest element of li.active with the class 'nav'

cy.get('li.active').closest('.nav')

The commands above will display in the Command Log as:

Command Log closest

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

console.log closest

See also