Check if an element contains a class in JavaScript?

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

提交回复
热议问题