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

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

Remove CSS class from element with JavaScript (no jQuery)

javascripthtmlcss

提问by Amra

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.

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

回答by Paul Rouget

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

正确且标准的方法是使用classList. 它现在在大多数现代浏览器的最新版本中得到广泛支持

ELEMENT.classList.remove("CLASS_NAME");

remove.onclick = () => {
  const el = document.querySelector('#el');
  if (el.classList.contains("red")) {
    el.classList.remove("red");

  }
}
.red {
  background: red
}
<div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button>

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

文档:https: //developer.mozilla.org/en/DOM/element.classList

回答by ЯegDwight

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyIDis the ID of the element and MyClass is the name of the class you wish to remove.

其中MyID是元素的 ID,MyClass 是您要删除的类的名称。



UPDATE:To support class names containing dash character, such as "My-Class", use

更新:要支持包含破折号字符的类名,例如“My-Class”,请使用

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\s)'+ 'My-Class' + '(?:\s|$)'), ' ');

回答by Matthew

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

这里有一种方法可以将此功能直接烘焙到所有 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;
}

回答by Keith Rousseau

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,' ');
        }
    }

回答by joseconstela

回答by Duncan

Edit

编辑

Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.

好的,完全重写。已经有一段时间了,我学到了一些东西,评论也很有帮助。

Node.prototype.hasClass = function (className) {
    if (this.classList) {
        return this.classList.contains(className);
    } else {
        return (-1 < this.className.indexOf(className));
    }
};

Node.prototype.addClass = function (className) {
    if (this.classList) {
        this.classList.add(className);
    } else if (!this.hasClass(className)) {
        var classes = this.className.split(" ");
        classes.push(className);
        this.className = classes.join(" ");
    }
    return this;
};

Node.prototype.removeClass = function (className) {
    if (this.classList) {
        this.classList.remove(className);
    } else {
        var classes = this.className.split(" ");
        classes.splice(classes.indexOf(className), 1);
        this.className = classes.join(" ");
    }
    return this;
};



Old Post旧帖

我只是在处理这样的事情。这是我想出的解决方案...

// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
    Object.defineProperty(String.prototype,'trim', {
        value: function() {
            return this.replace(/^\s+|\s+$/g,'');
        },
        writable:false,
        enumerable:false,
        configurable:false
    });
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
    value: function(c) {
        if(this.className.indexOf(c)<0) {
            this.className=this.className+=' '+c;
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double 
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
    value: function(c) {
        this.className=this.className.replace(c,'').replace('  ',' ').trim();
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});

Now you can call myElement.removeClass('myClass')

现在你可以打电话 myElement.removeClass('myClass')

or chain it: myElement.removeClass("oldClass").addClass("newClass");

或链接它: myElement.removeClass("oldClass").addClass("newClass");

回答by LivinKalai

It's very simple, I think.

这很简单,我想。

document.getElementById("whatever").classList.remove("className");

回答by scunliffe

try:

尝试:

function removeClassName(elem, name){
    var remClass = elem.className;
    var re = new RegExp('(^| )' + name + '( |$)');
    remClass = remClass.replace(re, '');
    remClass = remClass.replace(/ $/, '');
    elem.className = remClass;
}

回答by Tornike

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

回答by aaa

All of these answers are way too complicated, try

所有这些答案都太复杂了,试试

var string = "Hello, whats on your mind?";
var new_string = string.replace(', whats on your mind?', '');

The result would be a return of the string

结果将是字符串的返回

Hello

Super easy. Credits go to jondavidjohn Remove portion of string in Javascript

超级容易。学分转到 jondavidjohn在 Javascript 中删除部分字符串