jQuery Tutorial
jQuery Introduction jQuery Getting Started jQuery Syntax jQuery Selectors jQuery Events
jQuery Effects
jQuery Hide/Show jQuery Fade jQuery Slide jQuery Animation jQuery stop() jQuery Callback jQuery Chaining
jQuery Manipulation
jQuery Get/Set jQuery Add jQuery Remove jQuery CSS Classes jQuery css() jQuery Dimensions
jQuery Traversing
jQuery Traversing jQuery Ancestors jQuery Descendants jQuery Siblings jQuery Filtering
jQuery AJAX
jQuery AJAX Intro jQuery Load jQuery Get/Post jQuery AJAX Events
jQuery Misc
jQuery noConflict() jQuery Filters
jQuery References
jQuery Reference jQuery Selectors jQuery Events jQuery Effects jQuery HTML/CSS jQuery Traversing jQuery AJAX jQuery Miscellaneous jQuery Properties

jQuery Traversing Ancestors

With jQuery we can easily traverse up the DOM tree to find ancestors of an element.

An ancestor is a parent, grandparent, great-grandparent, and so on.

In this chapter we will explain how to traverse up the DOM tree.


Traversing Up the DOM Tree

We have the following jQuery methods that are used for traverse up the DOM tree:

The following section will show you how to use each method.


jQuery parent() Method

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

This method only travels a single level up the DOM tree.

The following example returns the direct parent of the SPAN element:

div (great-grand-parent)
div (grand-parent)

p (direct parent) span

Run code

You can also use an optional parameter to filter the search for parent.

The following example returns the direct parent element of each paragraph with a class "selected":

Run code

jQuery parents() Method

The jQuery parents() method returns all ancestor elements of the selected element.

This method traverse upwards from the parent element along ancestors of DOM elements, all the way up to the document's root element (<html>).

The following example returns all ancestors of the SPAN element:

body (great-great-grand-parent)
div (great-grand-parent)
div (grand-parent)

p (direct parent) span

Run code

jQuery parentsUntil() Method

The jQuery parentsUntil() method returns all ancestor elements between two given arguments.

The following example returns all ancestor elements between a SPAN and a BODY element:

body (great-great-grand-parent)
div (great-grand-parent)
div (grand-parent)

p (direct parent) span

Run code

jQuery Traversing Reference

For a complete Traversing methods reference, visit our jQuery Traversing Reference.