除了一个类之外,删除所有类

我知道,通过一些 jQuery 操作,我们可以向一个特定的 div 添加大量的类:

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

假设通过一些点击和其他操作 div 得到了很多类

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

那么,我怎样才能移除除了一个以外的所有类呢? 我想到的唯一想法是这样的:

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

虽然 removeClass()杀死了所有的类,div 被搞砸了,但是在 addClass('cleanstate')之后它又回到了正常状态。另一种解决方案是将 ID 属性与基本的 CSS 属性放在一起,这样它们就不会被删除,这也提高了性能,但是我只想知道另一种解决方案来除去除了“。清洁状态”

我问这个问题是因为,在实际的脚本中,div 经历了类的各种更改。

79335 次浏览

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

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

With plain old JavaScript, not JQuery:

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