Check if class exists somewhere in parent - vanilla JS

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

    My example for Vanilla JS, it's use a vanilla equivalent of parents() from jQuery

    var htmlElement = <htmlElement>,
        parents = [],
        classExist;
    while (htmlElement = htmlElement.parentNode.closest(<parentSelector>)) {
        parents.push(htmlElement);
    }
    classExist = (parents > 0);
    

    So your selector just to be a .className

    And just check if parent is > 0

    0 讨论(0)
  • 2020-12-09 08:47

    The fiddle

    The code

    function hasClass(element, className) {
      var regex = new RegExp('\\b' + className + '\\b');
      do {
        if (regex.exec(element.className)) {
          return true;
        }
        element = element.parentNode;
      } while (element);
      return false;
    }
    

    OR

    function hasClass(element, className) {
      do {
        if (element.classList && element.classList.contains(className)) {
          return true;
        }
        element = element.parentNode;
      } while (element);
      return false;
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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;
    }
    <div>
      <ul class="list">
        <li>
          <a id="child" href="#">i have a parent</a> 
        </li>
      </ul>
    </div>
    
    <div>
      <ul>
        <li>
          <a id="orphan" href="#">im an orphan</a> 
        </li>
      </ul>
    </div>
    
    <div id="output"></div>

    0 讨论(0)
  • 2020-12-09 08:53

    Try the closest() function - For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. Refer to the Official Docs here.

    0 讨论(0)
  • 2020-12-09 08:55

    Because ID must be unique on document context, you could just use instead:

    return !!document.querySelector('.the-class #the-element');
    

    If you want to include element itself, you can use:

    return !!document.querySelector('.the-class #the-element, #the-element.the-class');
    
    0 讨论(0)
提交回复
热议问题