An ancestor is a parent, grandparent, great-grandparent, and so on.
With jQuery, you can easily traverse UP the DOM tree to find the ancestors of any element.
This is very useful for styling container elements dynamically based on user interaction.
Three incredibly useful jQuery methods exist for traversing up the DOM tree:
parent()parents()parentsUntil()The parent() method returns the direct parent element of the selected element.
This method only traverses exactly one single level up the DOM tree.
$(document).ready(function(){
// Changes the direct parent of to have a red border
$("span").parent().css({"color": "red", "border": "2px solid red"});
});
The parents() method returns ALL ancestor elements of the selected element.
It will traverse all the way up to the document's root element (<html>).
$(document).ready(function(){
// Styles ALL ancestors of the element
$("span").parents().css({"color": "blue", "border": "2px solid blue"});
});
You can also filter the search by passing a parameter.
For example, $("span").parents("ul") will only return the ancestors that are specifically <ul> elements.
The parentsUntil() method returns all ancestor elements between two given arguments.
This is perfect for selecting a specific slice of the DOM tree without going all the way to the top.
$(document).ready(function(){
// Returns elements between span and div (the ul and li)
$("span").parentsUntil("div").css({"color": "green", "border": "2px solid green"});
});
Which method would you use to find only the DIRECT parent of an element?