Open In App

JQuery | Get the n-th level parent of an element

Given an element from DOM, The task is to find the n-th level parent of that element using JQuery. Below few of the methods are discussed:

Syntax: 



$(selector).on(event, childSel, data, fun, map)

Parameters: 

Syntax: 



$(selector).parents()

Syntax: 

$(selector).eq(index)

Parameter: 

Example 1: This example uses the parents() and eq() method to find the 0th level parent of class=’child’ element which is a <div> element. 




<!DOCTYPE HTML>
<html>
<head>
    <title>
        JQuery | Get the n-th level parent of an element.
    </title>
</head>
<script src=
</script>
  
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p id="GFG_UP" style="font-size: 17px; font-weight: bold;">
    </p>
    <div class="parent">
        <div class="child">
            child
        </div>
    </div>
    <br>
    <button>
        click here
    </button>
    <p id="GFG_DOWN" style="color: green;
            font-size: 24px;
            font-weight: bold;">
    </p>
    <script>
        $('#GFG_UP').text('Click on the button to see result');
        $('button').on('click', function () {
            $('.child').parents().eq(0).css({
                "color": "green",
                "border": "2px solid green"
            });
            $('#GFG_DOWN').text(
                "Border drawn around the first parent " +
                "of element with class = 'child'");
        });
    </script>
</body>
</html>

Output:

 

Example 2: This example uses the parents() and eq() method to find the 2nd level parent of class=’child’ element which is a <body> element. 




<!DOCTYPE HTML>
<html>
<head>
    <title>
        JQuery| Get the n-th level parent of an element.
    </title>
</head>
<script src=
</script>
  
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p id="GFG_UP" style="font-size: 17px; font-weight: bold;">
    </p>
    <div class="parent">
        <div class="child">
            child
        </div>
    </div>
    <br>
    <button>
        click here
    </button>
    <p id="GFG_DOWN" style="color: green;
            font-size: 24px;
            font-weight: bold;">
    </p>
    <script>
        $('#GFG_UP').text('Click on the button to see result');
        $('button').on('click', function () {
            $('.child').parents().eq(2).css({
                "border": "2px solid green"
            });
            $('#GFG_DOWN').text(
                "Border drawn around the third parent " +
                "of element with class = 'child'");
        });
    </script>
</body>
</html>

Output:

 


Article Tags :