Skip to content

Instantly share code, notes, and snippets.

@brwnll
Last active April 5, 2018 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brwnll/ac214abbb27ab3679bc17eb5f9b5fe4e to your computer and use it in GitHub Desktop.
Save brwnll/ac214abbb27ab3679bc17eb5f9b5fe4e to your computer and use it in GitHub Desktop.
/**
*
* @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