Skip to content

Instantly share code, notes, and snippets.

@droid001
Last active April 12, 2016 13:00
Show Gist options
  • Save droid001/eb6f1da0ea19e71d4bc2 to your computer and use it in GitHub Desktop.
Save droid001/eb6f1da0ea19e71d4bc2 to your computer and use it in GitHub Desktop.
Returns the closest parent element to a given element matching the provided selector, optionally including the element itself
/**
* @param {Element} el
* @param {string} selector
* @param {boolean} [includeSelf]
* @return {Element|null}
*/
const closestParent = function(el, selector, includeSelf) {
var parent = el.parentNode;
// polyfill
window.Element && function(ElementPrototype) {
ElementPrototype.matchesSelector = ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function(selector) {
var node = this,
nodes = (node.parentNode || node.document).querySelectorAll(selector),
i = -1;
while (nodes[++i] && nodes[i] != node);
return !!nodes[i];
}
}(Element.prototype);
if (includeSelf && el.matches(selector)) {
return el;
}
while (parent && parent !== document.body) {
if (parent.matches && parent.matches(selector)) {
return parent;
} else if (parent.parentNode) {
parent = parent.parentNode;
} else {
return null;
}
}
return null;
};
export default closestParent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment