什么是使用纯JavaScript的"hasClass"函数?

Kyl*_*yle 278 javascript dom

你如何hasClass用简单的'JavaScript' 来做jQuery ?例如,

<body class="foo thatClass bar">
Run Code Online (Sandbox Code Playgroud)

什么是JavaScript方式询问是否<body>thatClass

Dam*_*ien 838

只需使用classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}
Run Code Online (Sandbox Code Playgroud)

其他用途classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');
Run Code Online (Sandbox Code Playgroud)

浏览器支持:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • 歌剧11.50
  • Safari 5.1

classList 浏览器支持

  • 这应该是2018年以来接受的答案. (14认同)
  • 这应该是 2020 年以来可以接受的答案。因为没有人再谈论 IE8 / WinXP 了。 (8认同)
  • 同意。.. IE8 死了。IE 总体来说已经死了。这应该是前进的方向。 (6认同)
  • @iono在来自MDN的[Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)实现描述中,有一个垫片可以扩展对此行为的支持到IE8 https://developer.mozilla.org/en-US/docs/Web/API/Element/classList (5认同)
  • **这在IE8**中不受支持.IE8可以将`.classList`作为字符串检索,但它不会识别更现代的方法,如`.classList.contains()` (4认同)
  • 我同意@AlexanderWigmore,这非常有帮助和简单. (2认同)

SLa*_*aks 117

你可以检查是否element.className匹配/\bthatClass\b/.
\b匹配一个分词.

或者,您可以使用jQuery自己的实现:

var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 ) 
Run Code Online (Sandbox Code Playgroud)

要回答更一般的问题,您可以在github或源代码中查看jQuery的源代码,hasClass特别是在此源查看器中.

  • 用于jQuery实现的+1(用于查找(这是正确的英语吗?)`rclass`实际上是什么;)) (6认同)
  • 不会`\ b`匹配"thatClass-anotherClass"? (6认同)
  • @FelixSchwarz是对的,在当前的jQuery中,regexp更新为`/ [\ t\r \n \n\f]/g`.另外值得一提的是`/\bclass\b /`对于带有`-`减号的类名来说可能会失败(除了它工作正常),这就是为什么jQuery的实现更好,更可靠.例如:`/\bbig\b/.test('big-text')`返回true而不是false. (4认同)
  • 只是为了完整性:最近版本中的rclass是"/ [\n\t\r \n]/g"(\ r \n添加) (3认同)

rav*_*ren 35

最有效的一个班轮

  • 返回一个布尔值(而不是Orbling的答案)
  • 在搜索thisClass具有的元素时不会返回误报class="thisClass-suffix".
  • 与至少IE6的每个浏览器兼容

function hasClass( target, className ) {
    return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
Run Code Online (Sandbox Code Playgroud)


小智 28

// 1. Use if for see that classes:

if (document.querySelector(".section-name").classList.contains("section-filter")) {
  alert("Grid section");
  // code...
}
Run Code Online (Sandbox Code Playgroud)
<!--2. Add a class in the .html:-->

<div class="section-name section-filter">...</div>
Run Code Online (Sandbox Code Playgroud)

  • @greg_diesel:不要劝阻答案!对于常见问题的新解决方案非常受欢迎. (4认同)
  • @Raveren虽然欢迎新问题的新解决方案,但这个特别的答案并没有带来任何新的东西.它只会给这个问题增加噪音. (2认同)

Orb*_*ing 25

存储正在使用的类的属性是className.

所以你可以说:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个位置向你展示jQuery如何做所有事情,我会建议:

http://code.jquery.com/jquery-1.5.js


Gaw*_*win 12

hasClass函数:

HTMLElement.prototype.hasClass = function(cls) {
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] == cls) {
            return true;
        }
    }
    return false;
};
Run Code Online (Sandbox Code Playgroud)

addClass函数:

HTMLElement.prototype.addClass = function(add) {
    if (!this.hasClass(add)){
        this.className = (this.className + " " + add).trim();
    }
};
Run Code Online (Sandbox Code Playgroud)

removeClass函数:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName.trim();
};
Run Code Online (Sandbox Code Playgroud)


the*_*dnp 11

我使用简单/最小化解决方案,一行,跨浏览器,并与旧版浏览器一起使用:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'
Run Code Online (Sandbox Code Playgroud)

这种方法很棒,因为不需要填充,如果你使用它,classList它在性能方面要好得多.至少对于我来说.

更新:我制作了一个小型的polyfill,这是我现在使用的全面解决方案:

function hasClass(element,testClass){
  if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better

//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
  return false;
}
Run Code Online (Sandbox Code Playgroud)

对于其他类操作,请在此处查看完整文件.

  • 这次旅行是否会经过`notmyClassHere`类? (2认同)
  • 您还可以询问您的班级是否也不存在!! / myClass / .test(document.body.className)`注意`!`符号。 (2认同)
  • 这不是完美的,因为它不是子字符串证明。例如,当document.body.className ='myClass123'时,/ myClass / .test(document.body.className)返回true ... (2认同)

小智 9

一个很好的解决方案是使用classList和contains.

我是这样做的:

... for ( var i = 0; i < container.length; i++ ) {
        if ( container[i].classList.contains('half_width') ) { ...
Run Code Online (Sandbox Code Playgroud)

所以你需要你的元素并检查类的列表.如果其中一个类与您搜索的类相同,则返回true,否则返回false!


man*_*ela 9

这个“hasClass”函数适用于 IE8+、FireFox 和 Chrome:

hasClass = function(el, cls) {
    var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
        target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
    return target.className.match(regexp);
}
Run Code Online (Sandbox Code Playgroud)

[2021 年 1 月更新] 更好的方法:

hasClass = (el, cls) => {
  [...el.classList].includes(cls); //cls without dot
};
Run Code Online (Sandbox Code Playgroud)

  • Node.contains 用于子节点。使用 [... ] 它将 DOMTokenList 转换为节点类的数组。要搜索我使用的数组,包括 (2认同)

Ale*_*nez 6

使用类似的东西:

Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');
Run Code Online (Sandbox Code Playgroud)

  • 如果`classList`有一个`contains`方法,那么使用`[] .indexOf`有什么意义呢? (5认同)
  • 这不等于`myHTMLSelector.classList.indexOf('the-class')`?你最近还想要`> = 0`吗? (3认同)

Ale*_*hyi 5

if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
    // has "thatClass"
}
Run Code Online (Sandbox Code Playgroud)


Gra*_*ler 5

元素匹配()

$(element).hasClass('example')您可以element.matches('.example')在纯 JavaScript 中使用,而不是在 jQuery中:

if (element.matches('.example')) {
  // Element has example class ...
}
Run Code Online (Sandbox Code Playgroud)

查看浏览器兼容性

  • 应该是最重要的答案。 (3认同)