polyfills/Closest.js

/**
 * @module Polyfills
 */

/**
 * Polyfill for the native `Element.closest( selector )` function.
 * Finds the closest ancestor that matches the included selector.
 * More info here: [https://developer.mozilla.org/en-US/docs/Web/API/Element/closest](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest)
 */
const Closest = {
	polyfill() {
		if ( ! Element.prototype.matches ) {
			Element.prototype.matches = Element.prototype.msMatchesSelector
										|| Element.prototype.webkitMatchesSelector;
		}

		if ( ! Element.prototype.closest ) {
			Element.prototype.closest = function ( s ) { // eslint-disable-line func-names
				let el = this;

				do {
					if ( el.matches( s ) ) return el;
					el = el.parentElement || el.parentNode;
				} while ( null !== el && 1 === el.nodeType );

				return null;
			};
		}
	},
};

export default Closest;