W3cubDocs

/Cypress

closest

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

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.url().closest()     // Errors, 'url' 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 .closest().

Option Default Description
log true Displays the command in the Command log
timeout defaultCommandTimeout Time 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 until the element(s) exist in the DOM.

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

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

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