Remove all classes except one

[亡魂溺海] 提交于 2019-11-28 05:36:05

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

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

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

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

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

With plain old JavaScript, not JQuery:

document.getElementById("container").className = "cleanstate";
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:

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

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

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

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.

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

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"]);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!