jquery parent select - more efficient way

2019-02-24 05:01发布

问题:

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

$(draggable).parent().parent().parent().attr('entityid')

回答1:

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



回答2:

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.