English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery Traversal - Ancestor

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

Ancestor is parents, grandparents, great-grandparents, and so on.

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

Traverse the DOM tree

We have the following jQuery methods for traversing the DOM tree:

This chapter will show you how to use each method.

jQuery parent() method

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

This method moves up one level on the DOM tree.

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

div (great-grandparent)
div (grandparent)

p (direct parent)                  span

Run Code

You can also use optional parameters to filter the search parent item.

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

$(document).ready(function(){
  $("p").parent(".selected").css("background", "coral");
});
Test see if‹/›

jQuery parents() Method

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

This method traverses up the DOM element's ancestors from the parent element to the root element of the document (<html>).

The following example returns all ancestors of the SPAN element:

body (great-great-grandparent)
div (great-grandparent)
div (grandparent)

p (direct parent)                  span

Run Code

jQuery ParentUntil() Method

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

The following example returns all ancestor elements between the SPAN and BODY elements below:

body (great-great-grandparent)
div (great-grandparent)
div (grandparent)

p (direct parent)                  span

Run Code

jQuery Traversal Reference

For a complete reference of traversal methods, please visit ourjQuery Traversal Reference.