Check if an element contains a class in JavaScript?

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

    Since he wants to use switch(), I'm surprised no one has put this forth yet:

    var test = document.getElementById("test");
    var testClasses = test.className.split(" ");
    test.innerHTML = "";
    for(var i=0; i<testClasses.length; i++) {
        switch(testClasses[i]) {
            case "class1": test.innerHTML += "I have class1<br/>"; break;
            case "class2": test.innerHTML += "I have class2<br/>"; break;
            case "class3": test.innerHTML += "I have class3<br/>"; break;
            case "class4": test.innerHTML += "I have class4<br/>"; break;
            default: test.innerHTML += "(unknown class:" + testClasses[i] + ")<br/>";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:28

    Here is a little snippet If you’re trying to check wether element contains a class, without using jQuery.

    function hasClass(element, className) {
        return element.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className);
    }
    

    This accounts for the fact that element might contain multiple class names separated by space.

    OR


    You can also assign this function to element prototype.

    Element.prototype.hasClass = function(className) {
        return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
    };
    

    And trigger it like this (very similar to jQuery’s .hasClass() function):

    document.getElementById('MyDiv').hasClass('active');
    
    0 讨论(0)
  • 2020-11-22 10:28

    Tip: Try to remove dependencies of jQuery in your projects as much as you can - VanillaJS.

    document.firstElementChild returns <html> tag then the classList attribute returns all classes added to it.

    if(document.firstElementChild.classList.contains("your-class")){
        // <html> has 'your-class'
    } else {
        // <html> doesn't have 'your-class'
    }
    
    0 讨论(0)
提交回复
热议问题