Check if an element contains a class in JavaScript?

后端 未结 27 2225
面向向阳花
面向向阳花 2020-11-22 09:36

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

Currently, I\'m doing this:

相关标签:
27条回答
  • 2020-11-22 10:21

    See this Codepen link for faster and easy way of checking an element if it has a specific class using vanilla JavaScript~!

    hasClass (Vanilla JS)

    function hasClass(element, cls) {
        return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
    }
    
    0 讨论(0)
  • 2020-11-22 10:22

    Element.matches()

    element.matches(selectorString)

    According to MDN Web Docs:

    The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

    Therefore, you can use Element.matches() to determine if an element contains a class.

    const element = document.querySelector('#example');
    
    console.log(element.matches('.foo')); // true
    <div id="example" class="foo bar"></div>

    View Browser Compatibility

    0 讨论(0)
  • 2020-11-22 10:24

    I've created a prototype method which uses classList, if possible, else resorts to indexOf:

    Element.prototype.hasClass = Element.prototype.hasClass || 
      function(classArr){
        var hasClass = 0,
            className = this.getAttribute('class');
      
        if( this == null || !classArr || !className ) return false;
      
        if( !(classArr instanceof Array) )
          classArr = classArr.split(' ');
    
        for( var i in classArr )
          // this.classList.contains(classArr[i]) // for modern browsers
          if( className.split(classArr[i]).length > 1 )  
              hasClass++;
    
        return hasClass == classArr.length;
    };
    
    
    ///////////////////////////////
    // TESTS (see browser's console when inspecting the output)
    
    var elm1 = document.querySelector('p');
    var elm2 = document.querySelector('b');
    var elm3 = elm1.firstChild; // textNode
    var elm4 = document.querySelector('text'); // SVG text
    
    console.log( elm1, ' has class "a": ', elm1.hasClass('a') );
    console.log( elm1, ' has class "b": ', elm1.hasClass('b') );
    console.log( elm1, ' has class "c": ', elm1.hasClass('c') );
    console.log( elm1, ' has class "d": ', elm1.hasClass('d') );
    console.log( elm1, ' has class "a c": ', elm1.hasClass('a c') );
    console.log( elm1, ' has class "a d": ', elm1.hasClass('a d') );
    console.log( elm1, ' has class "": ', elm1.hasClass('') );
    
    console.log( elm2, ' has class "a": ', elm2.hasClass('a') );
    
    // console.log( elm3, ' has class "a": ', elm3.hasClass('a') );
    
    console.log( elm4, ' has class "a": ', elm4.hasClass('a') );
    <p class='a b c'>This is a <b>test</b> string</p>
    <svg xmlns="http://www.w3.org/2000/svg" width="100px" height="50px">
        <text x="10" y="20" class='a'>SVG Text Example</text>
    </svg>

    Test page

    0 讨论(0)
  • 2020-11-22 10:24

    This is supported on IE8+.

    First we check if classList exists if it does we can use the contains method which is supported by IE10+. If we are on IE9 or 8 it falls back to using a regex, which is not as efficient but is a concise polyfill.

    if (el.classList) {
      el.classList.contains(className);
    } else {
      new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
    }
    

    Alternatively if you are compiling with babel you can simply use: el.classList.contains(className);

    0 讨论(0)
  • 2020-11-22 10:26

    I created these functions for my website, I use only vanilla javascript, maybe it will help someone. First I created a function to get any HTML element:

    //return an HTML element by ID, class or tag name
        var getElement = function(selector) {
            var elements = [];
            if(selector[0] == '#') {
                elements.push(document.getElementById(selector.substring(1, selector.length)));
            } else if(selector[0] == '.') {
                elements = document.getElementsByClassName(selector.substring(1, selector.length));
            } else {
                elements = document.getElementsByTagName(selector);
            }
            return elements;
        }
    

    Then the function that recieve the class to remove and the selector of the element:

    var hasClass = function(selector, _class) {
            var elements = getElement(selector);
            var contains = false;
            for (let index = 0; index < elements.length; index++) {
                const curElement = elements[index];
                if(curElement.classList.contains(_class)) {
                    contains = true;
                    break;
                }
            }
            return contains;
        }
    

    Now you can use it like this:

    hasClass('body', 'gray')
    hasClass('#like', 'green')
    hasClass('.button', 'active')
    

    Hope it will help.

    0 讨论(0)
  • 2020-11-22 10:27

    A simplified oneliner:1

    function hasClassName(classname,id) {
     return  String ( ( document.getElementById(id)||{} ) .className )
             .split(/\s/)
             .indexOf(classname) >= 0;
    }
    

    1 indexOf for arrays is not supported by IE (ofcourse). There are plenty of monkey patches to be found on the net for that.

    0 讨论(0)
提交回复
热议问题