Skip to content Skip to sidebar Skip to footer

How To Get The Grandparent Of The Grandparent Of A Div In Html Using Jquery

Is there a better way to get the parent of the parent of the parent... like 5 times? So Instead of using this: $(this).parent().parent().parent().parent().parent() I could use som

Solution 1:

You can easily create your own function:

functiongetNthParentOf(elem,i) {
    while(i>0) {
        elem = elem.parent();
        i--;
    }
    return elem;
}

var something = getNthParentOf($(this),5);

Solution 2:

You can use the .parents traversing function in conjunction with the :nth() selector.

So the result will be something like:

$(this).parents(':nth(5)'));

Notice: the :nth() index starts from 0 so for your case it should be:

$(this).parents(':nth(4)'));

Solution 3:

If there are identifying markers on the parent element you want to get - such as an id or class you can use $(this).closest("#grandparentElement")

Solution 4:

Hope, this would be of any help.

try using .parentsUntil()

working example: http://jsfiddle.net/ylokesh/wLhcA/

Solution 5:

Well you can try

var parentControl = $('#yourcontrol').parent();
var grandParent = parentControl.parent();

Post a Comment for "How To Get The Grandparent Of The Grandparent Of A Div In Html Using Jquery"