Given a child element, is there a simple means of determining how many parent tags separate it from a given selector? Something like .closest(selector) which returns the number of parent() calls required to reach any element selected by the the given selector.
An (untested) implementation of what I’m looking for:
$.fn.distance = function(selector) {
var $parent = $(selector); // TODO check that element exists
var $current = $(this);
var depth = 0;
while ($current != $parent) {
$current = $current.parent();
++depth;
}
return depth;
}
1 Answer