Check if an element contains a class in JavaScript

檢查 class 清單中, 有沒有某一個字串的方法.

Syntax

var var_name = targetedElement.classList.contains("className");

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 😉

資料來源:
https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *