Check if class exists somewhere in parent - vanilla JS

前端 未结 10 839
时光说笑
时光说笑 2020-12-09 08:42

I\'m really struggling to see how to do this. I want to check if a class exsits somewhere in one of the parent elements of an element.

I don\'t want to use any libra

10条回答
  •  醉酒成梦
    2020-12-09 09:00

    You can use some and contains to achieve the result:

    function hasParentWithMatchingSelector (target, selector) {
      return [...document.querySelectorAll(selector)].some(el =>
        el !== target && el.contains(target)
      )
    }
    
    // usage
    hasParentWithMatchingSelector(myElement, '.some-class-name');
    

提交回复
热议问题