Traversing Up the DOM Tree
jQuery provides several methods to move upward through the DOM tree, from a selected element to its ancestors. The most commonly used methods are:
- parent() – Selects the immediate parent element.
- parents() – Selects all ancestor elements up the DOM tree.
- parentsUntil() – Selects all ancestor elements up to, but not including, a specified element.
jQuery parent() Method
The parent() method is used to get the direct parent of the selected element. It moves only one level up in the DOM hierarchy.
Example
The following code selects the immediate parent of each <span> element on the page:
$(document).ready(function(){
$("span").parent();
});
This method is useful when you want to access or style the container of an element without affecting higher-level ancestors.
jQuery parents() Method
The parents() method in jQuery is used to retrieve all ancestor elements of the selected element, climbing all the way up the DOM tree to the root <html> element.
This method is useful when you need to find or work with any containing elements above the current one—not just its immediate parent.
Example: Get All Ancestors
The following code selects all ancestor elements of every <span> on the page:
$(document).ready(function(){
$("span").parents();
});
Example: Filter Ancestors by Type
You can also pass an optional parameter to the parents() method to filter the results by element type.
The example below selects only the ancestor elements of <span> tags that are <ul> elements:
$(document).ready(function(){
$("span").parents("ul");
});
This is especially helpful when you're looking for a specific type of ancestor in a nested structure.
jQuery parentsUntil() Method
The parentsUntil() method in jQuery returns all ancestor elements between two specified elements in the DOM tree.
Unlike parents(), which returns all ancestors up to the <html> tag, parentsUntil() stops when it reaches the element you define as the boundary (excluding it from the result).
Example
The following code retrieves all ancestors of each <span> element up to but not including the nearest <div>:
$(document).ready(function(){
$("span").parentsUntil("div");
});
This method is useful when you want to limit your traversal to a specific range within the DOM hierarchy.