diff options
Diffstat (limited to 'js/utils/util.js')
-rw-r--r-- | js/utils/util.js | 41 |
1 files changed, 27 insertions, 14 deletions
diff --git a/js/utils/util.js b/js/utils/util.js index b3ffc73..68ff085 100644 --- a/js/utils/util.js +++ b/js/utils/util.js @@ -86,6 +86,23 @@ export const transformElement = ( element, transform ) => { } /** + * Element.matches with IE support. + * + * @param {HTMLElement} target The element to match + * @param {String} selector The CSS selector to match + * the element against + * + * @return {Boolean} + */ +export const matches = ( target, selector ) => { + + let matchesMethod = target.matches || target.matchesSelector || target.msMatchesSelector; + + return !!( matchesMethod && matchesMethod.call( target, selector ) ); + +} + +/** * Find the closest parent that matches the given * selector. * @@ -96,25 +113,21 @@ export const transformElement = ( element, transform ) => { * @return {HTMLElement} The matched parent or null * if no matching parent was found */ -export const closestParent = ( target, selector ) => { - - let parent = target.parentNode; +export const closest = ( target, selector ) => { - while( parent ) { - - // There's some overhead doing this each time, we don't - // want to rewrite the element prototype but should still - // be enough to feature detect once at startup... - let matchesMethod = parent.matches || parent.matchesSelector || parent.msMatchesSelector; + // Native Element.closest + if( typeof target.closest === 'function' ) { + return target.closest( selector ); + } - // If we find a match, we're all set - if( matchesMethod && matchesMethod.call( parent, selector ) ) { - return parent; + // Polyfill + while( target ) { + if( matches( target, selector ) ) { + return target; } // Keep searching - parent = parent.parentNode; - + target = target.parentNode; } return null; |