Introduction to jQuery
JQuery Syntax
JQuery Effects
JQuery HTML
JQuery Traversing
In jQuery, ancestor traversal means moving upward in the DOM tree from a selected element to its parent, grandparent, great-grandparent, etc.
jQuery provides several methods to go up the DOM tree—from a specific element to its parents, grandparents, and so on.
Method |
Description |
---|---|
.parent() |
Selects the immediate parent |
.parents() |
Selects all ancestors |
.parentsUntil() |
Selects ancestors up to a selector (exclusive) |
The .parent()
method returns the immediate parent of the selected element.
It goes one level up the DOM tree and returns only one element per match.
The following example returns the direct parent element of each <span>
elements:
Try it yourself
The .parents()
method gets all ancestor elements of the selected element, going all the way up the DOM tree until it reaches the <html>
element.
The following example returns all ancestors of all <span>
elements:
Try it yourself
.parents()
method — you can pass a selector as an optional parameter to filter the ancestors you want to target.
The following example returns all ancestors of all <span>
elements that are <div>
elements:
Try it yourself
The .parentsUntil()
method traverses up the DOM tree from the selected element and returns all ancestors up to (but not including) the element matched by the selector.
The following example returns all ancestor elements between a <span>
and a <div>
element:
Try it yourself