Check if class exists somewhere in parent - vanilla JS

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

    Another alternative for some those who like this style for modern/polyfilled browsers.

    const hasClass = (element, className) => {
        return element.classList.contains(className);
    };
    
    const hasParent = (element, className) => {
        if (!element.parentNode) {
            return false;
        }
    
        if (hasClass(element, className)) {
            return true;
        }
    
        return hasParent(element.parentNode, className)
    };
    

    Working demo:

    const hasClass = (element, className) => {
        return element.classList.contains(className);
    };
    
    const hasParent = (element, className) => {
        if (!element.parentNode) {
            return false;
        }
    
        if (hasClass(element, className)) {
            return true;
        }
    
        return hasParent(element.parentNode, className)
    };
    
    
    /* Demo Code, can ignore */
    const child = document.getElementById('child');
    const orphan = document.getElementById('orphan');
    const output = document.getElementById('output');
    
    const log = `child has parent? ${hasParent(child, 'list')}
    orphan has parent? ${hasParent(orphan, 'list')}
    `
    
    output.innerText = log;
    #output {
      margin-top: 50px;
      background: black;
      color: red;
      padding: 20px;
    }
    
    
    
    
    

提交回复
热议问题