Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Closest Selector from clicked item (starts on target and works up the tree)
// Adapted from https://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/
/**
* Get the closest matching element up the DOM tree.
* @private
* @param {Element} elem Starting element
* @param {String} selector Selector to match against
* @return {Boolean|Element} Returns null if not match found
*/
var getClosest = function(elem, selector) {
// Get closest match
for (; elem && elem !== document; elem = elem.parentNode) {
if (elem.matches(selector)) return elem;
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.