Last active
April 12, 2016 13:00
-
-
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
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
/** | |
* @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