Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery Traversal – Ancestors

jQuery Traversing - Ancestors


Ancestors are parents, grandparents, great-grandparents, and so on.

With jQuery, you can traverse up the DOM tree to find the ancestors of an element.


Traversing up the DOM tree

These jQuery methods are useful for traversing up the DOM tree:


jQuery parent() method

The parent() method returns the direct parent of the selected element.

This method only traverses one level up the DOM tree.

The following example returns the direct parent of each element:

Example

$

(

document

)

.

ready

(

function

(

)

{

$

(

"

span

"

)

.

parent

(

)

;

}

)

;

Try it »


jQuery parents() method

The parents() method returns all ancestor elements of the selected element, all the way up to the root element of the document ().

The following example returns all ancestors of the ... elements:

Example

$

(

document

)

.

ready

(

function

(

)

{

$

(

"

span

"

)

.

parents

(

)

;

}

)

;

Try it »

You can also use an optional parameter to filter the search for ancestor elements.

The following example returns all all ancestors of the ... element that are