Last active
April 5, 2018 22:54
-
-
Save brwnll/ac214abbb27ab3679bc17eb5f9b5fe4e to your computer and use it in GitHub Desktop.
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
/** | |
* | |
* @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