Created
January 20, 2021 13:02
-
-
Save caroillemann/db9fcf42cc863aa1faaeb502f488ff8c to your computer and use it in GitHub Desktop.
Finds an element's closest parent that matches the provided selector string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function findAncestor(el = null, selector) { | |
if (el.closest) { | |
return el.closest(selector); | |
} | |
// IE9+ polyfill | |
if (!Element.prototype.matches) { | |
Element.prototype.matches = Element.prototype.msMatchesSelector || | |
Element.prototype.webkitMatchesSelector; | |
} | |
var matches = el.matches || el.matchesSelector; | |
while (el) { | |
if (matches && matches.call(el, selector)) { | |
return el; | |
} | |
el = el.parentNode; | |
} | |
return null; | |
} | |
export default findAncestor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment