Remove CSS class from element with JavaScript (no

2018-12-31 12:32发布

This question already has an answer here:

Could anyone let me know how to remove a class on an element using JavaScript only? Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.

13条回答
十年一品温如言
2楼-- · 2018-12-31 13:23
div.classList.add("foo");
div.classList.remove("foo");

More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList

查看更多
美炸的是我
3楼-- · 2018-12-31 13:27

The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:

ELEMENT.classList.remove("CLASS_NAME");

Documentation: https://developer.mozilla.org/en/DOM/element.classList

查看更多
路过你的时光
4楼-- · 2018-12-31 13:28

Here's a way to bake this functionality right into all DOM elements:

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;
}
查看更多
步步皆殇っ
5楼-- · 2018-12-31 13:28

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.

查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 13:29

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="";
查看更多
与风俱净
7楼-- · 2018-12-31 13:30
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }
查看更多
登录 后发表回答