Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 something like this:

$(this).goBacktoNthParent(5);

Is it possible?

like image 280
Alon Avatar asked Feb 05 '12 15:02

Alon


2 Answers

Using the :eq() selector

The :eq() selector allows you to target the element at the zero-based index of the set that was matched...

$(this).parents(':eq(4)')

Note: use parent(s) selector

Because the selector is zero based, we gave it one less than the number targeted.

DEMO: http://jsfiddle.net/pmMFv/


Using the .eq() method

The .eq() method is effectively the same as its selector counterpart, allowing you to target the element at the zero-based index of the set that was matched...

$(this).parents().eq(4)

Note: use parent(s) selector

DEMO: http://jsfiddle.net/pmMFv/2/


Using parentNode in a loop

For greatest performance, we could use the .parentNode property of the element, and run it in a loop, updating a variable with the newest parent each time...

var el = this, i = 5;
while(i-- && (el = el.parentNode));

$(el)

DEMO: http://jsfiddle.net/pmMFv/1/

like image 125
5 revs, 2 users 96%user1106925 Avatar answered Sep 25 '22 05:09

5 revs, 2 users 96%user1106925


You can easily create your own function:

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

var something = getNthParentOf($(this),5);
like image 23
Niet the Dark Absol Avatar answered Sep 22 '22 05:09

Niet the Dark Absol