import isElementMatch from './isElementMatch';

/**
 * 获取离已知元素最近的匹配祖先元素（包括自身）
 * @param element {Element}
 * @param selector {String}
 * @param context {Element=}
 * @return {Element}
 *
 * @alias getMatchedWrapElement
 *
 * source by `dom-closest`
 * https://github.com/necolas/dom-closest.git
 *
 */
function getClosestElement(element, selector, context) {
  context = context || document;

  // guard against orphans
  element = {
    parentNode: element
  };

  while ((element = element.parentNode) && element !== context) {
    if (isElementMatch(element, selector)) {
      return element;
    }
  }

  return null;
}

export default getClosestElement;
