jQuery parents()Methods

jQuery 遍历方法jQuery Traversal Methods

Example

Return all ancestors of the <span> element:

$(document).ready(function(){
$("span").parents().css({"({"color":"red","border":"2px solid red"});
});

Result:

body (great-great-grandparent)
div (great-grandparent)
    ul (grandparent)
  • li (direct parent) span

Try it Yourself »

Definition and Usage

The parents() method returns all ancestor elements of the selected element.

Ancestors are parent, grandparent, great-grandparent, and so on.

DOM tree:This method traverses all ancestors of the DOM elements upward from the parent element, along all paths to the document root element (<html>).

Note:If the filter parameter is empty, this method selects all ancestors of the set of elements along all paths from the direct parent element up to <body> and <html>. Therefore, passing a selector expression to narrow down the search results is very useful.

This method andclosest()both traverse up the DOM tree; the difference is:

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 parameters

Syntax

$(selector).parents(filter)

Parameter Description
filter Optional. Specifies a selector expression to narrow down the search scope of ancestor elements.

Note:To return multiple ancestors, separate each expression with a comma.

实例

More Examples

Narrow the search scope
How to use the filter parameter to return the <ul> element among all ancestors of <span>.

Return multiple ancestors
How to use the filter parameter to return the <li> and <div> elements among all ancestors of <span>.

Demonstrate an element's ancestors by tag name
Demonstrate the ancestors of the <span> element.


jQuery 遍历方法jQuery Traversal Methods

Other Extensions