(($) => {
  $.plugin('closest', function(context) {
    let allMatching = [];
    this.some((node) => {
      let running = true;
      while(running) {
        let parent = node.parentNode, matches;

        if (parent.nodeType === 9) {
          return false;
        }

        matches = $.matches(parent, context);
        if (matches.length > 0) {
          running = false;
          allMatching.push(matches[0]);
          return true;
        } else {
          node = node.parentNode;
        }
      }
    });

    return $(allMatching[0]);
  });
})(collector);