jQuery find which parent is closer?

前端 未结 5 780
温柔的废话
温柔的废话 2021-01-13 17:52

In jQuery you can call closest to find the closest parent.

If I have a a in a li in a ul in a td in

5条回答
  •  天涯浪人
    2021-01-13 18:25

    Use .parents(). It returns a list of all parents that are ordered from closest to farthest.

    The difference between using this and using .closest(selector) is that it accepts a jQuery object instead of a selector string, which has to be hard coded. Meanwhile jQuery objects can be collections and so can be generated on the fly.

    (function($) {
      $.fn.getClosest = function(testElements) {
        var element = $(this);
        var parents = element.parents();
        var indexClosest = Number.MAX_VALUE;
        testElements.each(function() {
          var index = parents.index($(this));
          if (index > -1 && index < indexClosest)
            indexClosest = index;
        });
        return parents.eq(indexClosest);
      };
    })(jQuery);
    

    Use the function like this:

    $("a").getClosest($("table, ul"))
    

    Fiddle with advanced use case

提交回复
热议问题