Open In App

How to select all ancestors of an element in jQuery ?

Last Updated : 22 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 traverses all the levels up the selected element and returns all elements.

Syntax:

$(selector).parents()

Example: In this example, we are using the above method.

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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads