Remove all classes except one

前端 未结 6 1233
悲哀的现实
悲哀的现实 2020-12-08 06:37

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

L

6条回答
  •  一整个雨季
    2020-12-08 07:11

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

提交回复
热议问题