Skip to content

Instantly share code, notes, and snippets.

@brwnll
Last active Apr 5, 2018
Embed
What would you like to do?
/**
*
* @param {Object} el - A DOM node element
* @param {String} classname - The class name to search for
*/
function findNode(el = {}, classname = '') {
if (!el.className) el.className = '';
// Class will be exact match or space seperated
const firstOfMany = classname ' ';
const lastOfMany = ' ' + classname;
const middle = ' ' + firstOfMany;
if (el.className === classname
|| el.className.startsWith(firstOfMany)
|| el.className.endsWith(lastOfMany)
|| el.className.includes(middle)) {
// Has class, return element
return el;
}
// No class, if we haven't reached top of dom, iterate
if (el.parentNode) {
return findNode(el.parentNode, classname);
} else {
// we've run out of options
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment