Last active
August 5, 2020 21:53
-
-
Save beatrizsmerino/9475946cb42fe5aaba04fdc2ab49a281 to your computer and use it in GitHub Desktop.
Function getClosest. Get the parent element with a specific selector
This file contains 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 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