jQuery closest()
Method
Example
Return the first ancestor element of a <span>
, which is a <ul>
element:
$(document).ready(function(){
$("span").closest("ul").css({"color":"red","border":"2px solid red"});
});
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 upwards from the current element to the document root (<html>) to find the first ancestor element in the DOM.
This method is similar to parents(), both traversing upwards through the DOM tree, but with differences:
Starts from the current element
Traverses up the DOM tree and returns the first single ancestor that matches 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 that match the passed expression
Returns a jQuery object containing zero, one, or multiple elements
Other Related Methods:
parent() - Returns the direct parent of the selected element
parentsUntil() - Returns all ancestor elements between two given arguments
Syntax
Return the first ancestor element of the selected element:
Return the first ancestor element in the DOM tree found using DOM context:
Parameter | 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 a matching element can be found. |
More Examples
Return the first ancestor element of a <span>
, which is a <span>
element
Pass a DOM element as context to search for the first ancestor element