How can I check in JavaScript if a DOM element contains a class?

后端 未结 8 1224
长发绾君心
长发绾君心 2020-12-14 08:57

How can I check in JavaScript if a DOM element contains a class?

I tried the following code, but for some reason it doesn\'t work...

if (document.get         


        
8条回答
  •  醉梦人生
    2020-12-14 09:27

    The property you need is className, not class. Also, an element can have many classes, so if you want to test if it has a particular class you need to do something like the following:

    function hasClass(el, clss) {
        return el.className && new RegExp("(^|\\s)" +
               clss + "(\\s|$)").test(el.className);
    }
    
    var element = document.getElementById('element');
    if ( hasClass(element, "class_one") ) {
        // Do stuff here
    }
    

    UPDATE

    Modern browsers (pretty much everything major except IE <= 9) support a classList property, as mentioned in @Dropped.on.Caprica's answer. It therefore makes sense to use this where available. Here's some example code that detects whether classList is supported by the browser and falls back to the regex-based code otherwise:

    var hasClass = (typeof document.documentElement.classList == "undefined") ?
        function(el, clss) {
            return el.className && new RegExp("(^|\\s)" +
                   clss + "(\\s|$)").test(el.className);
        } :
        function(el, clss) {
            return el.classList.contains(clss);
        };
    

提交回复
热议问题