Is there a function similar to jQuery
.closest()
but for traversing descendants and returning only closest ones?
I know that there is
I think that first you have to define what "closest" means. If you mean the descendant node matching your criteria that is the shortest distance away in terms of parental links, then using ":first" or ".eq(0)" won't necessarily work:
In that example, the second ".target" Maybe: That's sort-of a hack plugin because of the way it builds the result object, but the idea is that you've got to find the shortest parental path out of all the matching elements you find. This code biases towards elements leftward in the DOM tree because of the element is "closer" to the "start"
$.fn.closestDescendant = function(sel) {
var rv = $();
this.each(function() {
var base = this, $base = $(base), $found = $base.find(sel);
var dist = null, closest = null;
$found.each(function() {
var $parents = $(this).parents();
for (var i = 0; i < $parents.length; ++i)
if ($parents.get(i) === base) break;
if (dist === null || i < dist) {
dist = i;
closest = this;
}
});
rv.add(closest);
});
return rv;
};
<
check; <=
would bias rightwards.