Check if an element contains a class in JavaScript?

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

    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');
    

提交回复
热议问题