Check if element contains any of the class from array

后端 未结 6 1036
一整个雨季
一整个雨季 2021-01-17 06:28

I have the following elements:

6条回答
  •  攒了一身酷
    2021-01-17 07:12

    How do I check if any of these elements has one of the classes in the array

    You'd have to iterate over elements and classes, and check if each element contain any of the classes in the array, something like this

    var elements = $('div');
    var obj      = ['nine', 'ten', 'eleven'];
    
    var hasClass = elements.filter(function(index, elem) {
        return obj.some(function(klass) {
            return elem.classList.contains(klass);
        });
    }).length > 0;
    

    You could easily make that into a function

    function hasClass(elements, classes) {
        return elements.filter(function(index, elem) {
            return classes.some(function(klass) {
                return elem.classList.contains(klass);
            });
        }).length > 0;
    }
    

    FIDDLE

    Using Array.some and Element.classList.contains to avoid uneccessary iteration and slow matching of classnames.

提交回复
热议问题