jQuery parents() method
Example
Return all ancestor elements of the:
$(document).ready(function(){
$("span").parents().css({"({"color":"red","border":"2px solid red"});
});
Result:
body (great-great-grandparent)
div (great-grandparent)
- li (direct parent) span
Try it »
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 up from the parent element along all paths of the DOM element's ancestors to the document root element ().
**Note:** If the filter parameter is empty, this method selects all ancestors in the element set along all paths from the direct parent element up to and. Therefore, passing a selector expression that narrows down the search results is very useful.
This method is similar to the closest() both traverse up the DOM tree; the differences are:
parents()
- 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
closest()
- starts from the current element
- traverses up the DOM tree and returns the first ancestor matching the passed expression
- returns a jQuery object containing zero or one element
Other related methods:
- parent() - returns the direct parent element of the selected element
- parentsUntil() - returns all ancestor elements between two given arguments
Syntax
$(
selector
).parents(
filter
)
| Parameters | Description |
|---|---|
| filter | Optional. Specifies a selector expression to narrow down the search for ancestor elements. |
**注意:**如需返回多个祖先,请使用逗号分隔每个表达式。 |
More examples
Narrow down the search
How to use the filter parameter to return among all ancestors of the
-
.
- and
.
Demonstrate ancestors of an element by tag name
Demonstrate ancestors of the element.
Return multiple ancestors
How to use the filter parameter to return among all ancestors of the
jQuery Traversal Methods