closest.js 864 B

123456789101112131415161718192021222324252627282930313233
  1. var DOCUMENT_NODE_TYPE = 9;
  2. /**
  3. * A polyfill for Element.matches()
  4. */
  5. if (typeof Element !== 'undefined' && !Element.prototype.matches) {
  6. var proto = Element.prototype;
  7. proto.matches = proto.matchesSelector ||
  8. proto.mozMatchesSelector ||
  9. proto.msMatchesSelector ||
  10. proto.oMatchesSelector ||
  11. proto.webkitMatchesSelector;
  12. }
  13. /**
  14. * Finds the closest parent that matches a selector.
  15. *
  16. * @param {Element} element
  17. * @param {String} selector
  18. * @return {Function}
  19. */
  20. function closest (element, selector) {
  21. while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
  22. if (typeof element.matches === 'function' &&
  23. element.matches(selector)) {
  24. return element;
  25. }
  26. element = element.parentNode;
  27. }
  28. }
  29. module.exports = closest;