Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active June 8, 2016 11:57
Show Gist options
  • Save vincentorback/e5383048738abff7a84f to your computer and use it in GitHub Desktop.
Save vincentorback/e5383048738abff7a84f to your computer and use it in GitHub Desktop.
Get closest parent element matching selector
/**
* Get closest DOM element up the tree that contains a class, ID, or data attribute
* @param {Node} elem The base element
* @param {String} selector The class, id, data attribute, or tag to look for
* @return {Node} Element or Null if no match
*/
export function getClosest (elem, selector) {
let firstChar = selector.charAt(0);
// Get closest match
for (; elem && elem !== document; elem = elem.parentNode ) {
// If selector is a class
if ( firstChar === '.' ) {
if ( elem.classList.contains( selector.substr(1) ) ) {
return elem;
}
}
// If selector is an ID
if ( firstChar === '#' ) {
if ( elem.id === selector.substr(1) ) {
return elem;
}
}
// If selector is a data attribute
if ( firstChar === '[' ) {
if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) {
return elem;
}
}
// If selector is a tag
if ( elem.tagName.toLowerCase() === selector ) {
return elem;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment