English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
We have the following jQuery methods for traversing the DOM tree:
This chapter will show you how to use each 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:
p (direct parent) span
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()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:
p (direct parent) span
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:
p (direct parent) span
For a complete reference of traversal methods, please visit ourjQuery Traversal Reference.