closest

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

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.
  • .closest() is a query, and it is safe to chain further methods.

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 until the element(s) exist in the DOM
  • .closest() will automatically retry until all chained assertions have passed

Timeouts

  • .closest() can time out waiting for the element(s) to exist in the DOM .
  • .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