Check if class exists somewhere in parent - vanilla JS

前端 未结 10 841
时光说笑
时光说笑 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 08:57

    I believe if( $('#the-element').parents('.the-class').length ) to be more efficient, but perhaps not as human-readable; which, with querySelector in the picture, could be replaced with the following method:

    function hasParent(element, parentSelector) {
        var potentialParents = document.querySelectorAll(parentSelector);
        for(i in potentialParents) if(potentialParents[i].contains(element))
            return potentialParents[i];
        return false;
    }
    

    That'd give you the ability to do:

    var elm = document.getElementById('the-element');
    if(hasParent(elm, '.the-class')) return true;
    

提交回复
热议问题