Phill Duffy
Phill Duffy

Reputation: 2866

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')

Upvotes: 5

Views: 3905

Answers (2)

moff
moff

Reputation: 6503

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

Upvotes: 9

peirix
peirix

Reputation: 37771

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.

Upvotes: 2

Related Questions