jQuery parent()Method

jQuery 遍历方法jQuery Traversal Methods

Example

Returns the direct parent element of <span>:

$(document).ready(function(){
$("span").parent().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 parent() method returns the direct parent element of the selected element.

DOM tree:This method only traverses a single level up the DOM tree. To traverse all the way up to the document root element (returning grandparent nodes or other ancestors), use theparents()orparentsUntil()method.

Tip:To traverse a single level down the DOM tree, or traverse all the way down to the last descendant (returning child nodes or other descendants), use thechildren()or find()method.


Syntax

$(selector).parent(filter)

Parameters Description
filter Optional. Specifies a selector expression to narrow down the search for the parent element.


实例

More Examples

Return the direct parent element of the <span> element
How to return the direct parent element of a <span> element.

Narrow down the search scope
How to use the filter parameter to return the <li> element with class name "1" among the parent elements of each <span>.

Return the <div> element from the direct parent of each <p> element
How to return the <div> element from among all direct parent elements of each <p> element.

Demonstrate the ancestor elements of an element by tag name
Demonstrates the ancestors of a <span> element.


jQuery 遍历方法jQuery Traversal Methods

Other Extensions