jQuery Ancestors

jQuery Traversing - Ancestors

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.


Traversing Up the DOM Tree

Three incredibly useful jQuery methods exist for traversing up the DOM tree:


The parent() Method

The parent() method returns the direct parent element of the selected element.

This method only traverses exactly one single level up the DOM tree.

The parent() Example:

$(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

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>).

The parents() Example:

$(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

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.

The parentsUntil() Example:

$(document).ready(function(){
  // Returns elements between span and div (the ul and li)
  $("span").parentsUntil("div").css({"color": "green", "border": "2px solid green"});
});

Exercise 1 of 1

?

Which method would you use to find only the DIRECT parent of an element?