I wrote this simple function in one of my TypeScript projects so i used querySelector on parentNode so you can pass to function class, id, tag name etc
findParentNode(el, selector:string):Element | null {
let found = null;
let child = el;
let childSelector = guessSelector(child);
while(child !== document && found === null) {
child = child.parentNode;
childSelector = guessSelector(child);
found = childSelector ? child.parentNode.querySelector(`${childSelector} > ${selector}`) : null;
}
return found;
function guessSelector(child:any):string {
childSelector = child.className ? `.${child.className.replace(' ', '.')}` : null;
if (typeof child.getAttribute === 'function') {
childSelector = !childSelector ?
(child.getAttribute('id') ? `#${child.getAttribute('id')}` : null) : childSelector;
childSelector = !childSelector ?
child.tagName.toLowerCase() : childSelector;
}
return childSelector;
}
}
Example:
If you want to find closest parent of target which has .param-input class you can do this like this:
document.body.addEventListener('click', (e) => {
console.log(findParentNode(e.target, '.param-input'));
});