Skip to content

Instantly share code, notes, and snippets.

@harmenjanssen
Last active September 22, 2018 18:53
Show Gist options
  • Save harmenjanssen/270d8cc6b98cdbc45b791426a025be49 to your computer and use it in GitHub Desktop.
Save harmenjanssen/270d8cc6b98cdbc45b791426a025be49 to your computer and use it in GitHub Desktop.
Walk up a DOM tree and return the matching element.
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);
});
*/
@harmenjanssen
Copy link
Author

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:

const getParentFn = node => node.parentNode;
const matchingParent = findInChain(matchFn, getParentFn, node);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment