Open In App

How to select specific ancestors of an element in jQuery ?

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

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

Syntax:

$(selector).parents()

Here selector is the selected element that all parents need to find. It returns all the parents of the selected element.

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

HTML




<!DOCTYpe html>
<html>
<head>
    <title>
        How to select specific ancestor
        elements of an element in jQuery?
    </title>
 
    <script src=
    </script>
 
    <script>
        $(document).ready(function () {
            $("li").parents("ul").css({
                color: "green",
                border: "2px solid green"
            });
        });
    </script>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        How to select specific 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
Previous
Next
Share your thoughts in the comments

Similar Reads