Javascript 检查元素是否具有类的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10960573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:47:26  来源:igfitidea点击:

What is the best way to check if element has a class?

javascriptdom

提问by Adam

The problem

问题

If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a particular class in the element's className property.

如果元素有多个类,那么它将与常规属性值检查不匹配,因此我正在寻找检查对象在元素的 className 属性中是否具有特定类的最佳方法。

Example

例子

// element's classname is 'hello world helloworld'
var element = document.getElementById('element');

// this obviously fails
if(element.className == 'hello'){ ... }

// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }  

So what would be the best way to do this?

那么最好的方法是什么?

just pure javascript please

请只是纯javascript

回答by Esailija

function hasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}

回答by ZER0

In modern browsers, you can use classList:

在现代浏览器中,您可以使用classList

if (element.classList.contains("hello")) {
   // do something
}  

In the browser that doesn't implement classListbut exposes the DOM's prototype, you can use the shim showed in the link.

在未实现classList但公开 DOM 原型的浏览器中,您可以使用链接中显示的 shim。

Otherwise, you can use the same shim's code to have a generic function without manipulate the prototype.

否则,您可以使用相同的 shim 代码来获得通用函数,而无需操作原型。

回答by Gor

this 2018 use ES6

这个 2018 使用 ES6

const hasClass = (el, className) => el.classList.contains(className);

How to use

如何使用

hasClass(document.querySelector('div.active'), 'active'); // true

回答by Endre Simo

This should work for you:

这应该适合你:

var a = [];
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];

    var re = new RegExp('\b' + classname + '\b');
    var els = node.getElementsByTagName("*");
    for(var i=0, j=els.length; i<j; i++)
        if(re.test(els[i].className)) a.push(els[i]);
        return a;
}

getElementsByClassName('wrapper');
for (var i=0; i< a.length; i++) {
    console.log(a[i].className);
}

This code will traverse the DOM and search for classes defined as parameter in the main function.Then it will test each founded class elements with a regexp pattern. If it founds will push to an array, and will output the results.

此代码将遍历 DOM 并搜索在主函数中定义为参数的类。然后它将使用正则表达式模式测试每个已建立的类元素。如果它发现将推送到一个数组,并将输出结果。

回答by Steve

You ask for pure javascript, so this is how jQuery implement it:

你要求纯 javascript,所以这就是 jQuery 实现它的方式:

    hasClass: function( selector ) {
        var className = " " + selector + " ",
            i = 0,
            l = this.length;
        for ( ; i < l; i++ ) {
            if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
                return true;
            }
        }
        return false;
    },

rclassis a regular expression of [\n\t\r], to ensure that alternative methods of delimiting class names are not an issue. thiswould be jQuery's reference to the object(s) and in a sense it makes the code more complicated than required, but it should make sense without knowing the details of it.

rclass是 , 的正则表达式[\n\t\r],以确保分隔类名的替代方法不成问题。this将是 jQuery 对对象的引用,从某种意义上说,它使代码比所需的更复杂,但在不知道它的细节的情况下应该是有意义的。

回答by Rodolphe BELOUIN

First, split the className by using the " " character, then check the index of the class you want to find.

首先,使用“”字符拆分className,然后检查要查找的类的索引。

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