jQuery Traversing - Ancestors


With jQuery you can skip the DOM tree to get the ancestors of something.

An ancestor is a parent, grandfather, ancestor, and so on.


Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:

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

jQuery parent() Method

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

This route exceeds only one level at the top of the DOM tree.

The following example returns the direct parent component of each element <span>:


Example
$(document).ready(function(){
  $("span").parent();
});


jQuery parents() Method

Parents() method returns all the ancestral features of the selected object, down to the root of the document (<html>).

The following example returns all the ancestors of all aspects of <span>:


Example
$(document).ready(function(){
  $("span").parents();
});

You can also use the optional parameter to filter your ancestor search.

The following example returns all the ancestors of all <span> elements <ul>:


Example
$(document).ready(function(){
  $("span").parents("ul");
});


jQuery parentsUntil() Method

parentsUntil() returns all ancestral traits between two given arguments.

The following example returns all the ancestral features between a <span> and <div> element:


Example
$(document).ready(function(){
  $("span").parentsUntil("div");
});