Check if an element contains a class in JavaScript?

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

    This is a little old, but maybe someone will find my solution helpfull:

    // Fix IE's indexOf Array
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement) {
            if (this == null) throw new TypeError();
            var t = Object(this);
            var len = t.length >>> 0;
            if (len === 0) return -1;
            var n = 0;
            if (arguments.length > 0) {
                n = Number(arguments[1]);
                if (n != n) n = 0;
                else if (n != 0 && n != Infinity && n != -Infinity) n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
            if (n >= len) return -1;
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
            for (; k < len; k++) if (k in t && t[k] === searchElement) return k;
            return -1;
        }
    }
    // add hasClass support
    if (!Element.prototype.hasClass) {
        Element.prototype.hasClass = function (classname) {
            if (this == null) throw new TypeError();
            return this.className.split(' ').indexOf(classname) === -1 ? false : true;
        }
    }
    

提交回复
热议问题