Last active
September 22, 2018 18:53
-
-
Save harmenjanssen/270d8cc6b98cdbc45b791426a025be49 to your computer and use it in GitHub Desktop.
Walk up a DOM tree and return the matching element.
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
const findInDomAncestry = predicate => node => | |
typeof node.nodeType === 'undefined' || node.nodeType === Node.DOCUMENT_NODE | |
? undefined | |
: predicate(node) | |
? node | |
: findInDomAncestry(predicate)(node.parentNode); | |
/* | |
Example usage: | |
const hasClass = cls => elm => elm.classList.contains(cls); | |
document.addEventListener('click', e => { | |
const target = findInDomAncestry(hasClass('foo-bar')(e.target); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Might be nice to abstract this further, to make it
findInChain
, where you provide the parent function.That would make it usable outside a DOM context as well: