Is there are more efficient way than the following for selecting the third parent?
$(draggable).parent().parent().parent().attr('entityid')
Is there are more efficient way than the following for selecting the third parent?
$(draggable).parent().parent().parent().attr('entityid')
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.
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