javascript 使用javascript删除类

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

Remove class using javascript

javascript

提问by Stranger

I need to remove the specific class attribute from all the element in the page. That is we need to remove the particular class from all the elements of the current html page. We only have the class name as the reference (which we need to remove from that page) and nothing else.

我需要从页面中的所有元素中删除特定的类属性。也就是说,我们需要从当前 html 页面的所有元素中删除特定的类。我们只有类名作为引用(我们需要从该页面中删除它),没有别的。

Please note that i cannot use anything as reference like id or another classand also i cannot use any JavaScript libraries for this also...

请注意,我不能使用任何东西作为参考,比如 id 或其他类,而且我也不能为此使用任何 JavaScript 库......

Any suggestion on this would be greatly appreciated.

对此的任何建议将不胜感激。

Also note that the class we need to remove will not be there more than twice.

还要注意,我们需要删除的类不会超过两次。

回答by ZER0

If you're using a modern browser:

如果您使用的是现代浏览器:

var forEach = Array.prototype.forEach;
var className = "yourclass";

forEach.call(document.querySelectorAll("." + className), function(node) {
    node.classList.remove(className);
});

See: forEach, querySelectorAlland classListfor further details.

有关更多详细信息,请参阅:forEachquerySelectorAllclassList

回答by gion_13

function removeClass(className) {
    // convert the result to an Array object
    var els = Array.prototype.slice.call(
        document.getElementsByClassName(className)
    );
    for (var i = 0, l = els.length; i < l; i++) {
        var el = els[i];
        el.className = el.className.replace(
            new RegExp('(^|\s+)' + className + '(\s+|$)', 'g'),
            ''
        );
    }
}

and just use it as :

并将其用作:

removeClass('desired-class-name');

UPDATE: see the live demo : http://jsbin.com/eyuxur

更新:查看现场演示:http: //jsbin.com/eyuxur

回答by Pirokiko

Here is a way which can be slow on very large pages, but removes the class from all elements.

这是一种在非常大的页面上可能会很慢的方法,但会从所有元素中删除该类。

var list = document.getElementsByTagName('*');
for(var i=0; i < list.length; i++){
  list[i].className = list[i].className.replace('YourClassName','');
}