DOM / pure JavaScript solution to jQuery.closest() implementation?

后端 未结 8 1874
感动是毒
感动是毒 2020-12-06 00:26

Here\'s the markup i\'m trying to query. So given the markup:

8条回答
  •  清歌不尽
    2020-12-06 00:51

    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'));
    });
    

提交回复
热议问题