jQuery Descendants

jQuery Traversing - Descendants

A descendant is a child, grandchild, great-grandchild, and so on.

With jQuery, you can easily traverse DOWN the DOM tree to find descendants of an element.

This is highly useful for targeting nested items, like list items inside of a specific container.


Traversing Down the DOM Tree

There are two main jQuery methods used for traversing down the DOM tree:


The children() Method

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

This method only traverses exactly one single level down the DOM tree.

The children() Example:

$(document).ready(function(){
  // Styles only the direct children (the paragraphs) of the div
  $("div").children().css({"color": "red", "border": "2px solid red"});
});

You can also filter the results by passing a class or tag name.

For example, $("div").children("p.first") returns all direct children with the class name "first".


The find() Method

The find() method returns descendant elements all the way down to the last descendant.

Unlike children(), it does not stop at the first level.

You must provide a parameter to find() to tell it what to search for.

The find() Example:

$(document).ready(function(){
  // Searches through all levels inside the div to find a span
  $("div").find("span").css({"color": "blue", "border": "2px solid blue"});
});

Returning All Descendants

If you simply want to select every single element nested inside a container, you use the * selector.

Running $("div").find("*") will select and return absolutely everything inside the <div>.


Exercise 1 of 1

?

If you want to search deep into nested elements for a specific tag, which method must you use?