Skip to content

Instantly share code, notes, and snippets.

@beatrizsmerino
Last active August 5, 2020 21:53
Show Gist options
  • Save beatrizsmerino/9475946cb42fe5aaba04fdc2ab49a281 to your computer and use it in GitHub Desktop.
Save beatrizsmerino/9475946cb42fe5aaba04fdc2ab49a281 to your computer and use it in GitHub Desktop.
Function getClosest. Get the parent element with a specific selector
/**
* @function getClosest
* @description Get the parent element with a specific selector
* @param {Element} sonElement - Son node
* @param {String} parentSelector - Parent selector
* @returns {Element|null}
*/
function getClosest(sonElement, parentSelector) {
// Element.matches() polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) { }
return i > -1;
};
}
// Get the closest matching element
for (; sonElement && sonElement !== document; sonElement = sonElement.parentNode) {
if (sonElement.matches(parentSelector)) return sonElement;
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment