如何在没有 jQuery 的情况下在 Javascript 中添加和删除类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26736587/
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-22 23:18:46  来源:igfitidea点击:

How to add and remove classes in Javascript without jQuery

javascripthtml

提问by Peter Eberle

I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

我正在寻找一种快速且安全的方法来在没有 jQuery 的情况下从 html 元素中添加和删除类。
它也应该在早期的 IE(IE8 及更高版本)中工作。

采纳答案by Dan Bray

The following 3 functions work in browsers which don't support classList:

以下 3 个函数在不支持的浏览器中工作classList

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\s|^)' + className + '(\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\s|^)' + className + '(\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}

https://jaketrent.com/post/addremove-classes-raw-javascript/

https://jaketrent.com/post/addremove-classes-raw-javascript/

回答by Shoaib Chikate

Another approach to add the class to element using pure JavaScript

使用纯 JavaScript 将类添加到元素的另一种方法

For adding class:

添加类:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

对于删除类:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note:but not supported in IE <= 9 or Safari <=5.0

注意:但不支持 IE <= 9 或 Safari <=5.0

回答by Chris Ferdinandi

For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper

为了将来的友好性,我推荐使用 polyfill/shim 的 classList:https: //developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper

var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
    console.log('yep!');
}

回答by jongo45

classListis available from IE10 onwards, use that if you can.

classList从 IE10 开始可用,如果可以,请使用它。

element.classList.add("something");
element.classList.remove("some-class");

回答by zavg

To add class without JQuery just append yourClassNameto your element className

要在没有 JQuery 的情况下添加类,只需附加yourClassName到您的元素className

document.documentElement.className += " yourClassName";

document.documentElement.className += " yourClassName";

To remove class you can use replace()function

要删除类,您可以使用replace()函数

document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');

document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');

Also as @DavidThomas mentioned you'd need to use the new RegExp()constructor if you want to pass class names dynamically to the replace function.

同样正如@DavidThomas 提到的,new RegExp()如果您想将类名动态传递给替换函数,则需要使用构造函数。

回答by Yonatan Ayalon

Add & Remove Classes (tested on IE8+)

添加和删​​除类(在 IE8+ 上测试)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

将 trim() 添加到 IE(取自:JavaScript 中的 .trim() 不适用于 IE

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

添加和删​​除类:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

用法:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

一个有效的 JSFIDDLE:http: //jsfiddle.net/fixit/bac2vuz/1/

回答by Fahim Shah

I'm using this simple code for this task:

我正在使用这个简单的代码来完成这个任务:

CSS Code

CSS 代码

.demo {
     background: tomato;
     color: white;
}

Javascript code

Javascript代码

function myFunction() {
    /* Assign element to x variable by id  */
    var x = document.getElementById('para);

    if (x.hasAttribute('class') {      
        x.removeAttribute('class');     
    } else {
        x.setAttribute('class', 'demo');
    }
}

回答by Nalan Madheswaran

Try this:

尝试这个:

  const element = document.querySelector('#elementId');
  if (element.classList.contains("classToBeRemoved")) {
    element.classList.remove("classToBeRemoved");

  }

回答by Gil

When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().

当您从等式中删除 RegExp 时,您会留下不那么“友好”的代码,但仍然可以使用(远)不那么优雅的split()方式来完成。

function removeClass(classString, toRemove) {
    classes = classString.split(' ');
    var out = Array();
    for (var i=0; i<classes.length; i++) {
        if (classes[i].length == 0) // double spaces can create empty elements
            continue;
        if (classes[i] == toRemove) // don't include this one
            continue;
        out.push(classes[i])
    }
    return out.join(' ');
}

This method is a lot bigger than a simple replace()but at least it can be used on older browsers. And in case the browser doesn't even support the split()command it's relatively easy to add it using prototype.

这个方法比简单的replace()大很多,但至少它可以在旧浏览器上使用。如果浏览器甚至不支持split()命令,使用原型添加它相对容易。