I think you must first determine what "closest" means. If you mean a descendant of a node that matches your criteria, which is the shortest distance in terms of parent links, then using ": first" or ".eq (0)" will not necessarily work:
<div id='start'> <div> <div> <span class='target'></span> </div> </div> <div> <span class='target'></span> </div> </div>
In this example, the second element .target <span> is closer to start <div> because it has only one parent hop away. If this is what you mean by βclosest,β you need to find the minimum distance in the filter function. The list of results from the jQuery selector is always in DOM order.
May be:
$.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; };
This type of hacked plugin is due to the way it creates the result object, but the idea is that you need to find the shortest parent path of all the matching elements that you find. This code shifts to elements to the left in the DOM tree due to the check < ; <= will shift to the right.
Pointy Jan 22 '12 at 14:50 2012-01-22 14:50
source share