jQuery find which parent is closer?

前端 未结 5 778
温柔的废话
温柔的废话 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:30

    Here is a simple implementation of the .closer() method that returns the selector that is closest to the given element:

    $.fn.closer = function(varargs) {
      var $elem = $(this);
      while ($elem.length) {
        for (var i = 0, len = arguments.length; i < len; i++) {
          if ($elem.is(arguments[i])) {
            return arguments[i];
          }
        }
        $elem = $elem.parent();
      }
      return null;
    };
    

    See it in action on jsFiddle.

提交回复
热议问题