views:

444

answers:

2

Is there are more efficient way than the following for selecting the third parent?

$(draggable).parent().parent().parent().attr('entityid')
+2  A: 

If you have an id, class or tagname to go by you can do $(draggable).parents(element). But make sure it's unique enough that you'll get only one element, as parents() will retrieve multiple elements if found.

peirix
Thanks - the following suits my requirements:$(draggable).parents('.entity').attr('entityid')
Phill Duffy
+3  A: 

This should be faster, since we're using pure DOM instead of repeatedly attaching the parent to the jQuery object.

jQuery.fn.getParent = function(num) {
    var last = this[0];
    for (var i = 0; i < num; i++) {
        last = last.parentNode;
    }
    return jQuery(last);
};
// usage:
$('#myElement').getParent(3);

Working demo: http://jsbin.com/ecoze

moff
Nice implementation.
Matthew Flaschen
I like this method very much, I wanted to suggest using parentNode too, but you beat me to it.
Igor Zinov'yev
Thanks for the kind words, Matthew and Igor.
moff
Thanks for the code suggestion - I will try it out
Phill Duffy
Same can be achieved by `$("#myElement").parents(":eq(3)")`
Anand Chitipothu