Check if class exists somewhere in parent - vanilla JS

前端 未结 10 813
时光说笑
时光说笑 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:51

    You'll have to do it recursively :

    // returns true if the element or one of its parents has the class classname
    function hasSomeParentTheClass(element, classname) {
        if (element.className.split(' ').indexOf(classname)>=0) return true;
        return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
    }
    

    Demonstration (open the console to see true)

提交回复
热议问题