Latest web development tutorials

jQuery parents () method

jQuery traversal methods jQuery traversal methods

Examples

Back <span> all ancestor elements:

$(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"

Definition and Usage

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

Ancestors father, grandfather, great-grandfather, and so on.

DOM tree: This method traverses the ancestors up from the parent element DOM element, until all the path of the document root element (<html>).

Note: If the filter parameter is empty, the process directly from the parent element until the <body> and <html> select all paths of elements in the collection of all the ancestors. So pass a narrow scope of search results selector expression is very useful.

This method closest () are traverse up the DOM tree, the difference is:

parents ()

  • Starting from the parent element
  • Along the DOM tree traversal up and returns expression matches all ancestors passed
  • Returns zero, one or more elements of the jQuery object

closest ()

  • Starting from the current element
  • The first ancestor traversal along the DOM tree upwards, and returns the matching expression passed
  • Returns zero or one element of jQuery object

Other related methods:

  • parent () - Returns the direct parent element of the selected element
  • parentsUntil () - Returns all ancestors of the element parameters between the two to

grammar

$(selector).parents( filter )

参数 描述
filter 可选。规定缩小搜索祖先元素范围的选择器表达式。

注意:如需返回多个祖先,请使用逗号分隔每个表达式。

Examples

More examples

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

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

Demo by ancestor element tag name
Demo <span> element ancestors.


jQuery traversal methods jQuery traversal methods