jQuery closest() method
Example
Return the first ancestor element of the, which is a
-
element:
- starts from the current element
- traverses up the DOM tree and returns the first single ancestor matching the passed expression
- returns a jQuery object containing zero or one element
- starts from the parent element
- traverses up the DOM tree and returns all ancestors matching the passed expression
- returns a jQuery object containing zero, one, or more elements
- parent() - returns the direct parent element of the selected element
- parentsUntil() - returns all ancestor elements between two given arguments
$
(
document
)
.
ready
(
function
(
)
{
$
(
"
span
"
)
.
closest
(
"
ul
"
)
.
css
(
{
"
color
"
:
"
red
"
,
"
border
"
:
"
2px solid red
"
}
)
;
}
)
;
Try it »
Definition and Usage
The closest() method returns the first ancestor element of the selected element.
Ancestors are the parent, grandparent, great-grandparent, and so on.
**DOM Tree:** This method traverses up from the current element along all paths to the document root element () to find the first ancestor element of the DOM element.
This method is similar to the parents() are similar; both traverse up the DOM tree; the differences are:
closest()
parents()
Other related methods:
Syntax
Return the first ancestor element of the selected element:
$(
selector
).closest(
filter
)
Return the first ancestor element in the DOM tree found using a DOM context:
$(
selector
).closest(
filter,context
)
| Parameters | Description |
|---|---|
| filter | Required. Specifies a selector expression, element, or jQuery object to narrow down the search for ancestor elements. |
| context | Optional. A DOM element within which matching elements can be found. |
More examples
Return the first ancestor element of the, which is a Element
Because this method starts from the current element, it searches the first of the , will return .
passed as the context in a DOM element in order to search for the first ancestor element
using two arguments passed as the context in a DOM element to search for the first
jQuery Traversal Methods