In jQuery, ancestor methods are used to traverse up the DOM tree to locate parent elements or ancestors of a specific element. This is helpful for dynamically manipulating parent or ancestor elements based on the structure of the DOM.
Key Methods for Traversing Ancestors
.parent()
Selects the direct parent of the selected element..parents()
Selects all ancestor elements of the selected element, up to the root..parentsUntil()
Selects all ancestor elements between the selected element and the specified selector (excluding the specified selector).
Examples
Example 1: .parent()
<!DOCTYPE html> <html> <head> <title>jQuery .parent() Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { $("#child").click(function() { $(this).parent().css("border", "2px solid red"); }); }); </script> </head> <body> <div id="parent" style="padding: 10px;"> <p id="child" style="margin: 0; cursor: pointer;">Click me to highlight my parent!</p> </div> </body> </html>