jQuery closest()Methods
Examples
Return the first ancestor of <span>, which is a <ul> element:
Try it Yourself »
Definition and Usage
The closest() method returns the first ancestor of the selected element.
An ancestor is a parent, grandparent, great-grandparent, and so on.
DOM tree:This method traverses upward from the current element, all the way to the document root element (<html>), to find the first ancestor of a DOM element.
This method isparents()similar to ..., both traverse upward along the DOM tree, the difference is:
closest()
- Starts from the current element
- Traverses upward along the DOM tree and returns the first single ancestor that matches the passed expression
- Returns a jQuery object containing zero or one element
parents()
- Starts from the parent element
- Traverses upward along the DOM tree and returns all ancestors that match the passed expression
- Returns a jQuery object containing zero, one, or more elements
Other related methods:
- parent()- Returns the direct parent element of the selected element
- parentsUntil()- Returns all ancestors between two given parameters
Syntax
Return the first ancestor of the selected element:
Return the first ancestor in the DOM tree found using a DOM context:
| Parameters | Description |
|---|---|
| filter | Required. Specifies a selector expression, element, or jQuery object to narrow down the search range for ancestor elements. |
| context | Optional. A DOM element within which matching elements can be found. |
More Examples
Return the first ancestor of <span>, which is a <span> element
Because this method starts from the current element, it searches for the first <span> within <span> and will return that <span>.
Passing a DOM element as context to search for the first ancestor element
Using two parameters to pass a DOM element as the context, in order to search for the first <ul> element.
Other Extensions
jQuery Traversal Methods