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:
- parent()
- parents()
- parentsUntil()
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
-
element:
Example
$
(
document
)
.
ready
(
function
(
)
{
$
(
"
span
"
)
.
parents
(
"
ul
"
)
;
}
)
;
Try it »
jQuery parentsUntil() method
The parentsUntil() method returns all ancestor elements between two given elements.
The following example returns all ancestor elements between The difference between
Example
$
(
document
)
.
ready
(
function
(
)
{
$
(
"
span
"
)
.
parentsUntil
(
"
div
"
)
;
}
)
;
Try it »