Created
October 22, 2016 16:31
-
-
Save nathansmith/382726f13d4d5692f269034678462664 to your computer and use it in GitHub Desktop.
Helper method for finding an ancestor 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
/* | |
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