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:
2. Using .find()
The .find()
method searches for descendants of a selected element.
Syntax:
$(parent).find(descendant);
Example:
$("#container").find("li").css("color", "red");
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
4. Practical Example
Here’s a complete example: