jQuery parents()
Method
Example
Return all ancestor elements of the <span>
:
Result:
- li (direct parent)
Definition and Usage
The parents()
method returns all ancestor elements of the selected element.
Ancestors are the parent, grandparent, great-grandparent, and so on.
DOM Tree: This method traverses the ancestors of the DOM element from the parent upwards until it reaches the document root element (<html>).
Note: If the filter parameter is empty, the method will select all ancestors from the direct parent up to <body>
and <html>
. Therefore, passing a selector expression to narrow down the search results is very useful.
This method is similar to closest() in that both traverse up the DOM tree, but with the following differences:
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
Starts from the current element
Traverses up the DOM tree and returns the first ancestor that matches the passed expression
Returns a jQuery object containing zero or one element
Other Related Methods:
parent() - Returns the direct parent of the selected element
parentsUntil() - Returns all ancestors between two given arguments
Syntax
Parameter | Description |
---|---|
filter | Optional. Specifies a selector expression to narrow down the search for ancestor elements. <br> <br> Note: To return multiple ancestors, separate each expression with a comma. |
More Examples
Demonstrate Ancestors by Tag Name