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
.error
with the class 'banner'
Find the closest element of the 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
li.active
with the class 'nav'
Find the closest element of cy.get('li.active').closest('.nav')
The commands above will display in the Command Log as:
When clicking on the closest
command within the command log, the console
outputs the following: