Last active
March 30, 2020 08:19
-
-
Save Dobby89/ba967b77fe2da5f4f596c6337c78fb52 to your computer and use it in GitHub Desktop.
Find the closest element to the target element
This file contains hidden or 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
/** | |
* 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; | |
} |
This file contains hidden or 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
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