DOM Traversing is the process of moving through your HTML structure based on the relationship between elements. The "Ancestors" group of methods allows you to move **upward** in the DOM tree to find an element's parent, grandparent, or even great-grandparent.
jQuery provides three essential methods for finding an element's ancestors:
| Method | Description |
|---|---|
parent() |
Returns the direct parent of the element. |
parents() |
Returns all ancestors up to the `<html>` root. |
parentsUntil() |
Returns all ancestors **between** two given elements. |
The parent() method only travels a single level up the DOM tree. It targets
the immediate container of the selected element.
// Finds the direct parent of all <span> elements
$("span").parent().css({"color": "red", "border": "2px solid red"});
The parents() method targets every single ancestor. You can also pass a
selector to this method to filter the ancestor you are looking for.
// Targets ALL ancestors of all <span> elements
$("span").parents();
// Targets only <ul> ancestors of all <span> elements
$("span").parents("ul").css("background-color", "yellow");
The parentsUntil() method returns all ancestor elements between the selected
element and the element specified in the parentheses.
// Returns all ancestors between <span> and <div>
$("span").parentsUntil("div");
A common use case for parent() is to highlight a form group when its
internal
input field is focused.
$("input").focus(function() {
// Highlight the direct container (likely a .form-group div)
$(this).parent().css("background-color", "#f0f8ff");
});
$("input").blur(function() {
$(this).parent().css("background-color", "transparent");
});
.closest() method is often more efficient than
.parents().
.parents("div")).