Similar to jQuery .closest() but traversing descendants?

后端 未结 16 723
情书的邮戳
情书的邮戳 2020-12-07 15:13

Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is

16条回答
  •  一整个雨季
    2020-12-07 15:46

    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" element is "closer" to the "start"

    , because it's only one parental hop away. If that's what you mean by "closest", you'd need to find the minimum distance in a filter function. The result list from a jQuery selector is always in DOM order.

    Maybe:

    $.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;
    };
    

    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 < check; <= would bias rightwards.

提交回复
热议问题