Javascript 删除除一个之外的所有类

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

Remove all classes except one

javascriptjqueryclassaddclassremoveclass

提问by DarkGhostHunter

Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:

好吧,我知道通过一些 jQuery 操作,我们可以向特定的 div 添加很多类:

<div class="cleanstate"></div>

Let's say that with some clicks and other things, the div gets a lot of classes

假设通过一些点击和其他事情,div 获得了很多类

<div class="cleanstate bgred paddingleft allcaptions ..."></div>

So, how I can remove all the classes except one? The only idea I have come up is with this:

那么,我如何删除除一个之外的所有类?我想出的唯一想法是:

$('#container div.cleanstate').removeClass().addClass('cleanstate');

While removeClass()kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate')it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"

虽然removeClass()杀死了所有类,但 div 被搞砸了,但在此之后添加addClass('cleanstate')它会恢复正常。另一种解决方案是将 ID 属性与基本 CSS 属性一起放置,这样它们就不会被删除,这也提高了性能,但我只想知道另一种解决方案来摆脱除“.cleanstate”之外的所有内容

I'm asking this because, in the real script, the div suffers various changes of classes.

我问这个是因为,在真实的脚本中,div 会遭受各种类的变化。

回答by Yahel

Instead of doing it in 2 steps, you could just reset the entire value at once with attrby overwriting all of the class values with the class you want:

您可以attr通过用您想要的类覆盖所有类值来一次重置整个值,而不是分两步进行:

jQuery('#container div.cleanstate').attr('class', 'cleanstate');

Sample: http://jsfiddle.net/jtmKK/1/

示例:http: //jsfiddle.net/jtmKK/1/

回答by tvanfosson

Use attrto directly set the class attribute to the specific value you want:

使用attr直接将 class 属性设置为您想要的特定值:

$('#container div.cleanstate').attr('class','cleanstate');

回答by Rob at TVSeries.com

With plain old JavaScript, not JQuery:

使用普通的旧 JavaScript,而不是 JQuery:

document.getElementById("container").className = "cleanstate";

回答by Nizzy

Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:

有时由于 CSS 动画,您需要保留一些类,因为一旦删除所有类,动画可能无法正常工作。相反,您可以保留一些类并删除其余类,如下所示:

$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');

回答by rob

regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla

关于抢劫答案,为了完整性,您还可以将 querySelector 与 vanilla 一起使用

document.querySelector('#container div.cleanstate').className = "cleanstate";

回答by No one

What if if you want to keep one or more than one classes and want classes except these. These solution would not work where you don't want to remove all classes add that perticular class again. Using attr and removeClass() resets all classes in first instance and then attach that perticular class again. If you using some animation on classes which are being reset again, it will fail.

如果您想保留一个或多个类并且想要除这些类之外的类,该怎么办。如果您不想删除所有类并再次添加该特定类,这些解决方案将不起作用。 使用 attr 和 removeClass() 在第一个实例中重置所有类,然后再次附加该特定类。如果您在再次重置的类上使用某些动画,它将失败。

If you want to simply remove all classes except some class then this is for you. My solution is for: removeAllExceptThese

如果您想简单地删除除某个类之外的所有类,那么这适合您。我的解决方案是:removeAllExceptThis

Array.prototype.diff = function(a) {
            return this.filter(function(i) {return a.indexOf(i) < 0;});
        };
$.fn.removeClassesExceptThese = function(classList) { 
/* pass mutliple class name in array like ["first", "second"] */
            var $elem = $(this);

            if($elem.length > 0) {
                var existingClassList = $elem.attr("class").split(' ');
                var classListToRemove = existingClassList.diff(classList);
                $elem
                    .removeClass(classListToRemove.join(" "))
                    .addClass(classList.join(" "));
            }
            return $elem;
        };

This will not reset all classes, it will remove only necessary.
I needed it in my project where I needed to remove only not matching classes.

这不会重置所有类,它只会删除必要的。
我在我的项目中需要它,我只需要删除不匹配的类。

You can use it $(".third").removeClassesExceptThese(["first", "second"]);

你可以使用它 $(".third").removeClassesExceptThese(["first", "second"]);