Check if an element contains a class in JavaScript?

后端 未结 27 2186
面向向阳花
面向向阳花 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:10

    Try this one:

    document.getElementsByClassName = function(cl) {
       var retnode = [];
       var myclass = new RegExp('\\b'+cl+'\\b');
       var elem = this.getElementsByTagName('*');
       for (var i = 0; i < elem.length; i++) {
           var classes = elem[i].className;
           if (myclass.test(classes)) retnode.push(elem[i]);
       }
        return retnode;
    };
    
    0 讨论(0)
  • 2020-11-22 10:12

    For me the most elegant and faster way to achieve it is:

    function hasClass(el,cl){
       return !!el.className && !!el.className.match(new RegExp('\\b('+cl+')\\b'));
    }
    
    0 讨论(0)
  • Use element.classList .contains method:

    element.classList.contains(class);
    

    This works on all current browsers and there are polyfills to support older browsers too.


    Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:

    function hasClass(element, className) {
        return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
    }
    

    Otherwise you will also get true if the class you are looking for is part of another class name.

    DEMO

    jQuery uses a similar (if not the same) method.


    Applied to the example:

    As this does not work together with the switch statement, you could achieve the same effect with this code:

    var test = document.getElementById("test"),
        classes = ['class1', 'class2', 'class3', 'class4'];
    
    test.innerHTML = "";
    
    for(var i = 0, j = classes.length; i < j; i++) {
        if(hasClass(test, classes[i])) {
            test.innerHTML = "I have " + classes[i];
            break;
        }
    }
    

    It's also less redundant ;)

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

    The easy and effective solution is trying .contains method.

    test.classList.contains(testClass);
    
    0 讨论(0)
  • 2020-11-22 10:15

    className is just a string so you can use the regular indexOf function to see if the list of classes contains another string.

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

    Here's a case-insensitive trivial solution:

    function hasClass(element, classNameToTestFor) {
        var classNames = element.className.split(' ');
        for (var i = 0; i < classNames.length; i++) {
            if (classNames[i].toLowerCase() == classNameToTestFor.toLowerCase()) {
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题