Skip to content
Related Articles

Related Articles

How to select all ancestors of an element in jQuery ?

Improve Article
Save Article
  • Last Updated : 24 Mar, 2021
Improve Article
Save Article

In this article, we will select all the ancestor elements of an element in jQuery. To select all ancestor elements of an element, the parents() method is used. This method is used to find all the parent elements related to the selected element. This method traverse all the levels up the selected element and return that all elements.

Syntax:

$(selector).parents()

Example:

HTML




<!DOCTYpe html>
<html>
  
<head>
    <title>
        How to select all ancestor elements 
        of an element in jQuery?
    </title>
  
    <script src=
    </script>
  
    <style>
        .gfg {
            border: 2px solid green;
        }
    </style>
  
    <script>
        $(document).ready(function () {
            $("li").parents().addClass("gfg");
        });
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to select all ancestor elements 
        of an element in jQuery?
    </h3>
  
    <p>GeeksforGeeks Subjects List-</p>
  
    <ul>
        <li>HTML</li>
        <li>CSS</li>
        <li>JavaScript</li>
        <li>PHP</li>
    </ul>
</body>
  
</html>

Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!