Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Created October 22, 2016 16:31
Show Gist options
  • Save nathansmith/382726f13d4d5692f269034678462664 to your computer and use it in GitHub Desktop.
Save nathansmith/382726f13d4d5692f269034678462664 to your computer and use it in GitHub Desktop.
Helper method for finding an ancestor element.
/*
This method works similarly
to jQuery's `closest` method.
```
$('.foo').closest('.bar')
```
Except, instead of returning an
element, it executes a function.
Used like this…
```
const el = closest(e.target, function (el) {
// Get class name.
const c = el.className
// Check validity.
if (
typeof c === 'string' &&
c.match('foo-class__here')
) {
return el
}
})
```
*/
function closest (el, fn) {
// Exit.
if (el === document.documentElement) {
return
}
// Proceed.
return el && (
fn(el)
? el
: closest(el.parentNode, fn)
)
}
// Export.
export default closest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment