Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery parent select - more efficient way

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

$(draggable).parent().parent().parent().attr('entityid')
like image 621
Phill Duffy Avatar asked Dec 29 '22 20:12

Phill Duffy


1 Answers

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

like image 160
moff Avatar answered Jan 08 '23 02:01

moff