English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery closest() method

jQuery Traversal Methods

The closest() method returns the first ancestor of the selected element.

The closest() method traverses from the current element up to the root element of the document (<html>) to find the first ancestor of the DOM element.

closest() andparents()The methods are similar because they both traverse the DOM tree. The differences are as follows:

closest()

  • Start from the current element

  • Move up the DOM tree until an object matching the provided selector is found

  • The returned jQuery object contains zero or one element for each element in the original collection in document order

parents()

  • Start from the parent element

  • Navigate to the root element of the DOM tree, adding each ancestor element to a temporary collection; then, if there is a selector, filter the collection based on the selector

  • The returned jQuery object contains zero or more elements (in the reverse document order) from each element in the original collection

Syntax:

Return the first ancestor of the selected element:

$(selector).closest(selectorExpression)

Use DOM context to return the first ancestor in which to search the DOM tree:

$(selector).closest(selectorExpression, context)

Example

Return the first ancestor of <span>, which is the <div> element:

body (great-great-grandparent)
div (great-grandparent)
div (grandparent)
div (first ancestor-grandparent)

p (direct parent)                      span

Run Code

Parameter Value

ParameterDescription
selectorExpressionSpecify a selector expression, element, or jQuery object to match elements
contextOptional: You can find the DOM elements that match the elements in it

jQuery Traversal Methods