jQuery – Find Ancestors of an element

An Ancestor is a parent, grandparent, great grand-parent of an element. Let us see the figure again:

jQuery Traversing

In the above figure, the Ancestor is <div>. The following are the key points about Ancestors from the above figure:

  • The <div> is the parent of <ul> and <ol>
  • The <ul> element is the parent of both the <li> elements
  • The <ol> element is the parent of both the <li> elements
  • The left child of the <ul> is <li>. This <li> is the parent of both the <span> elements
  • The left and right child of the <ol> is <li>. This <li> is the parent of <strong>

Ancestors suggest traversing up in the DOM tree and the following are the supported methods in jQuery:

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

Let us learn about each method one by one:

The parent() method in jQuery

The jQuery parent() method returns the direct parent element of the selected element. Let us see an example wherein we will return the direct parent of the <span> element:

Output

jQuery parent() method

The parents() method in jQuery

The jQuery parents() method returns all the ancestor elements of the selected element. Let us see an example wherein we will return the ancestors of the <span> element:

Output

jQuery parents() method

The parentsUntil() method in jQuery

If you want to return the ancestors between two elements, then use the parentsUntil() method in jQuery. Let us see an example wherein we will return the ancestors between <span> and <div>:

Output

jQuery parentsUntil() method

Introduction to jQuery Traversing
jQuery - Find Descendants of an element
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading