易学问答
  • 首页
  • 话题
  • 动态
  • 专家
  • 文章
  • 作者
  • 公告
  • 更多
    • 积分规则
登录 或 注册
  • 首页
  • 话题
  • 动态
  • 专家
  • 文章
  • 作者
  • 公告
  • 积分规则
 发表新帖
发表新帖

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

后端 未结
关注
 8  1301
长发绾君心
长发绾君心 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:38

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

    testElement.classList.contains(className)
    

    Demo

    var testElement = document.getElementById('test');
    
    document.body.innerHTML = '
    ' + 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) + '
    ';


    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)
    查看其它8个回答
    提交评论

    •  加载中...
 看不清?
提交回复
热议问题