jQuery Descendants

In jQuery, descendants refer to all the child elements of a specific parent element, including nested children (grandchildren, great-grandchildren, etc.). To work with descendants in jQuery, you typically use descendant selectors or methods like .find().

 

1. Descendant Selector

The descendant selector in jQuery is written as:

$("parent descendant")

Try It Now

  • parent: The parent element.
  • descendant: The child or nested child elements you want to target.

Example:

<div id="container">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</div>

Try It Now

To select all <li> elements inside the <div>:

$("#container li").css("color", "blue");

Try It Now

This changes the text color of all <li> elements to blue.

 

2. Using .find()

The .find() method searches for descendants of a selected element.

Syntax:

$(parent).find(descendant);

Try It Now

Example:

$("#container").find("li").css("color", "red");

Try It Now

 

This also selects all <li> elements inside #container and changes their text color to red.

3. Filtering Descendants

You can further filter descendants using additional methods like .filter() or .eq().

Example:

Change the color of the second <li>:

$("#container li").eq(1).css("color", "green"); // Zero-based index

Try It Now

4. Practical Example

Here’s a complete example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Descendants</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="main">
    <p>This is a paragraph.</p>
    <div>
      <span>Nested span</span>
    </div>
  </div>

  <script>
    // Select all descendants of #main and change their text color
    $("#main *").css("color", "blue");

    // Find only the <span> inside #main
    $("#main").find("span").css("font-weight", "bold");
  </script>
</body>
</html>

Try It Now

Key Points:

  1. Use $("parent descendant") for simple descendant selection.
  2. Use .find() for a more focused search within descendants.
  3. Combine selectors and methods for advanced filtering.