检查元素是否包含JavaScript中的类? [英] Check if an element contains a class in JavaScript?

查看:60
本文介绍了检查元素是否包含JavaScript中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用普通的JavaScript(而不是jQuery),有什么方法可以检查元素是否包含一个类?

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

当前,我正在这样做:

var test = document.getElementById("test");
var testClass = test.className;

switch (testClass) {
  case "class1":
    test.innerHTML = "I have class1";
    break;
  case "class2":
    test.innerHTML = "I have class2";
    break;
  case "class3":
    test.innerHTML = "I have class3";
    break;
  case "class4":
    test.innerHTML = "I have class4";
    break;
  default:
    test.innerHTML = "";
}

<div id="test" class="class1"></div>

问题在于,如果我将HTML更改为此...

The issue is that if I change the HTML to this...

<div id="test" class="class1 class5"></div>

...不再存在完全匹配项,因此我得到默认输出为空("").但是我仍然希望输出为I have class1,因为<div>包含 .class1类.

...there's no longer an exact match, so I get the default output of nothing (""). But I still want the output to be I have class1 because the <div> still contains the .class1 class.

推荐答案

使用 element.classList .contains方法:

element.classList.contains(class);

这适用于所有当前浏览器,并且也有polyfill支持旧版本的浏览器.

This works on all current browsers and there are polyfills to support older browsers too.

或者,如果您使用的是较旧的浏览器,并且不想使用polyfill对其进行修复,请使用

Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:

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

否则,如果您要查找的班级是另一个班级名称的一部分,您还将获得true.

Otherwise you will also get true if the class you are looking for is part of another class name.

演示

jQuery使用类似(如果不相同)的方法.

jQuery uses a similar (if not the same) method.

应用于示例:

由于这不能与switch语句一起使用,因此可以通过以下代码实现相同的效果:

As this does not work together with the switch statement, you could achieve the same effect with this code:

var test = document.getElementById("test"),
    classes = ['class1', 'class2', 'class3', 'class4'];

test.innerHTML = "";

for(var i = 0, j = classes.length; i < j; i++) {
    if(hasClass(test, classes[i])) {
        test.innerHTML = "I have " + classes[i];
        break;
    }
}

它也不太冗余;)

这篇关于检查元素是否包含JavaScript中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆