Skip to content

Instantly share code, notes, and snippets.

@caroillemann
Created January 20, 2021 13:02
Show Gist options
  • Save caroillemann/db9fcf42cc863aa1faaeb502f488ff8c to your computer and use it in GitHub Desktop.
Save caroillemann/db9fcf42cc863aa1faaeb502f488ff8c to your computer and use it in GitHub Desktop.
Finds an element's closest parent that matches the provided selector string.
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