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

后端 未结 8 1226
长发绾君心
长发绾君心 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:35

    hasClass:

    function hasClass(element, className) {
      return (element.className).indexOf(className) > -1;
    }
    

    containsClass:

    function containsClass(element, className) {
      return Array.from(element.classList).filter(function (cls) {
        return cls.indexOf(className) > -1;
      }).length > 0;
    }
    

    codepen demo

    0 讨论(0)
  • 2020-12-14 09:38

    All modern browsers support the contains method of Element.classList :

    testElement.classList.contains(className)
    

    Demo

    var testElement = document.getElementById('test');
    
    document.body.innerHTML = '<pre>' + JSON.stringify({
        'main' : testElement.classList.contains('main'),
        'cont' : testElement.classList.contains('cont'),
        'content' : testElement.classList.contains('content'),
        'main-cont' : testElement.classList.contains('main-cont'),
        'main-content' : testElement.classList.contains('main-content')
    }, null, 2) + '</pre>';
    <div id="test" class="main main-content content"></div>


    Supported browsers

    (from CanIUse.com)


    Polyfill

    If you want to use Element.classList and you also want to support ancient browsers like IE8, consider using this polyfill by Eli Grey.

    0 讨论(0)
提交回复
热议问题