Skip to content

Latest commit

 

History

History
100 lines (63 loc) · 2.32 KB

File metadata and controls

100 lines (63 loc) · 2.32 KB
title
closest

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

{% note info %} The querying behavior of this command matches exactly how {% url .closest() http://api.jquery.com/closest %} works in jQuery. {% endnote %}

Syntax

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

Usage

{% fa fa-check-circle green %} Correct Usage

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

{% fa fa-exclamation-triangle red %} Incorrect Usage

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

Arguments

{% fa fa-angle-right %} selector (String selector)

A selector used to filter matching DOM elements.

{% fa fa-angle-right %} options (Object)

Pass in an options object to change the default behavior of .closest().

Option Default Description
log true {% usage_options log %}
timeout {% url defaultCommandTimeout configuration#Timeouts %} {% usage_options timeout .closest %}

Yields {% helper_icon yields %}

{% yields changes_dom_subject_or_subjects .closest %}

Examples

Selector

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

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

Rules

Requirements {% helper_icon requirements %}

{% requirements dom .closest %}

Assertions {% helper_icon assertions %}

{% assertions existence .closest %}

Timeouts {% helper_icon timeout %}

{% timeouts existence .closest %}

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:

{% imgTag /img/api/closest/find-closest-nav-element-in-test.png "Command Log closest" %}

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

{% imgTag /img/api/closest/closest-console-logs-elements-found.png "console.log closest" %}

See also

  • {% url .first() first %}
  • {% url .parent() parent %}
  • {% url .parents() parents %}
  • {% url .parentsUntil() parentsuntil %}
  • {% url .prev() prev %}
  • {% url .prevAll() prevall %}
  • {% url .prevUntil() prevuntil %}