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

jQuery Traversal - Descendants

With jQuery, we can easily traverse the DOM tree to find element descendants.

Descendants are children, grandchildren, great-grandchildren, and so on.

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

Traversing the DOM tree

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

Below, we will show you how to use each method.

jQuery children() method

jQuery children()The method returns all direct child elements of the selected element.

This method only traverses a single level in the DOM tree.

The following example returns all direct child elements of the DIV:

$("document").ready(function(){
  $("div").children().css("background-color", "coral");
});
Test See‹/›

You can also use optional parameters to filter search items.

The following example returns all <p> elements that are direct descendants of the DIV:

$("document").ready(function(){
  $("div").children("p").css("background-color", "coral");
});
Test See‹/›

jQuery find() Method

jQuery find()The method returns all descendant elements that match the specified parameters.

This method traverses down the DOM elements' descendants along the DOM tree, down to the last descendant.

Starting from all paragraphs and searching for descendant span elements, compared to $("p span"):

$("document").ready(function(){
  $("p").find("span").css("background", "mediumpurple");
});
Test See‹/›

To return multiple descendants, please separate the selector names with commas.

The following example returns all <span> and <i> elements that are descendants of the <p> element:

$("document").ready(function(){
  $("p").find("span, i").css("background", "mediumpurple");
});
Test See‹/›

jQuery Traversal Reference

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