jQuery Traversing - Ancestors


With jQuery, you can move upwards through the HTML structure to locate elements that are higher up in the hierarchy.

An ancestor is someone who came before you in your family tree, like your parents, grandparents, or even great-grandparents.


Traversing Up the DOM Tree

Here are three helpful jQuery techniques for moving upwards in the DOM tree:

  • parent()
  • parents()
  • parentsUntil()

jQuery parent() Method

The parent() function gives you the immediate parent of the element you've selected.

This technique only moves one level higher in the DOM tree.

In this example, we find the immediate parent element of every element


jQuery parents() Method

The parents() method gives you all the older elements of the chosen element, right up to the main document's beginning (<html>).

In this example, you'll find all the parent elements of every <span> element.

You can also use an extra option to narrow down your search for older generations.

This example finds all the parent elements of every <span> element which are inside <ul> elements:


jQuery parentsUntil() Method

The parentsUntil() function provides all the ancestor elements that exist between two specified elements.

In this example, we find all the parent elements between a <span> and a <div> element.