Skip to content

Instantly share code, notes, and snippets.

@Dobby89
Last active March 30, 2020 08:19
Show Gist options
  • Save Dobby89/ba967b77fe2da5f4f596c6337c78fb52 to your computer and use it in GitHub Desktop.
Save Dobby89/ba967b77fe2da5f4f596c6337c78fb52 to your computer and use it in GitHub Desktop.
Find the closest element to the target element
/**
* getClosest
*
* Find the closest element to the target element
*
* @param target - dom element which is the current element
* @param selector - the element you are looking for
* @param scope - limit the search to a containing element
* @returns {*}
*/
export function getClosest(target, selector, scope){
var matches = (scope || document).querySelectorAll(selector);
var i;
var el = target;
do {
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {};
} while ((i < 0) && (el = el.parentElement));
return el;
}
export function getClosest(
target: HTMLElement,
selector: string,
scope?: HTMLElement
): null | HTMLElement {
const matches = (scope || document).querySelectorAll(selector);
let i;
let el: null | HTMLElement = target;
do {
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {}
} while (i < 0 && (el = el.parentElement ? el.parentElement : null));
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment