Latest web development tutorials

jQuery traversal - ancestor

Ancestors father, grandfather or great-grandfather, and so on.

By jQuery, you are able to traverse up the DOM tree for ancestor elements.


Up to traverse the DOM tree

These jQuery methods are useful, they are used to traverse up the DOM tree:

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

jQuery parent () method

parent () method returns the immediate parent element of the selected element.

This method only up one pair DOM tree traversal.

The following example returns each <span> element's immediate parent element:

Examples

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

try it"


jQuery parents () method

parents () method returns the ancestor of all the elements of the selected element, it is all the way up until the root element of the document (<html>).

The following example returns all the ancestor of all <span> element:

Examples

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

try it"

You can also use the optional parameters to filter the search for ancestor elements.

The following example returns all the ancestor of all <span> element, and it is the <ul> element:

Examples

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

try it"


jQuery parentsUntil () method

parentsUntil () method returns the ancestor of all the elements between two given elements.

The following example returns the ancestor between all the elements <span> and <div> element between:

Examples

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

try it"