使用JavaScript从CSS元素中删除CSS类(不使用jQuery)

谁能让我知道如何仅使用JavaScript删除元素上的类?请不要给我jQuery的答案,因为我无法使用它,对此我一无所知。

LEYJim2020/03/12 10:52:33

There is also $.toggleClass, $.addClass, and $.removeClass. For documentation, take a look at http://api.jquery.com/toggleClass/.

Take a look at this jsFiddle example to see it in action.

Davaid神无2020/03/12 10:52:33

I use this JS snippet code :

First of all, I reach all the classes then according to index of my target class, I set className = "".

Target = document.getElementsByClassName("yourClass")[1];
Target.className="";
米亚小小神乐2020/03/12 10:52:33
div.classList.add("foo");
div.classList.remove("foo");

有关更多信息,访问https://developer.mozilla.org/en-US/docs/Web/API/element.classList

卡卡西达蒙西里2020/03/12 10:52:33

这是将此功能引入所有DOM元素的方法:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}