Descendants in Jquery
? What Are Descendants in jQuery?
In jQuery, descendants are elements that are nested inside another element. You can use jQuery to select and manipulate these child elements, even if they are deep within the HTML structure.
?? Basic Concept:
A descendant can be any element that is nested inside a parent element, whether it’s a direct child or a nested child at any level.
? Example Structure:
<div "#parent").find(".child").css("color", "blue");</script>
Explanation:
The
.find(".child")method selects all elements with the classchildthat are descendants of the#parentdiv.All
.childelements will have their text color changed to blue.
? Example 2: .children()
The .children() method selects direct children (not deeper descendants) of the selected element.
"#parent").children(".child").css("font-weight", "bold");</script>
Explanation:
.children(".child")selects only the direct.childelements that are immediate children of#parent.In this case, the
panddivelements with classchildwill become bold.
? Example 3: .closest()
The .closest() method is used to find the nearest ancestor (or self) that matches the given selector. It bubbles up the DOM tree to find the closest match.
"p").closest(".container").css("border", "2px solid red");</script>
Explanation:
The
pelement calls.closest(".container"), which finds the closest ancestor with the class.container.The
containerwill now have a red border.
? Example 4: .parents()
The .parents() method selects all ancestors (including the element itself) of the selected element that match a given selector.
"p").parents("#parent").css("background-color", "yellow");</script>
Explanation:
The
pelement calls.parents("#parent"), which selects all ancestors (in this case, just#parent) and applies a yellow background.
? Example 5: .parent()
The .parent() method selects the immediate parent of the selected element.
"p").parent().css("border", "3px solid blue");</script>
Explanation:
The
pelement calls.parent(), which selects the immediate parent (#parent) and applies a blue border.
? Key Differences Between .find(), .children(), and .parents()
.find(): Selects all descendants matching the selector..children(): Selects direct children (not deeper descendants)..parents(): Selects all ancestors, including the element itself.
? Summary:
.find(): Selects all descendants..children(): Selects direct children..closest(): Finds the nearest ancestor matching the selector..parents(): Selects all ancestors..parent(): Selects the immediate parent.