特定のクラスを除くすべてのクラスを要素から削除するにはどうすればよいですか。not を使用できないと仮定していますremoveClass()
。があり、<div class="aa bb cc dd ee ff"></div>
を除くすべてのクラスを削除したいとしますaa dd
。これどうやってするの。
7 に答える
少しきれいにするために、小さな拡張機能を作成できます。
jQuery.fn.removeClassExcept = function (val) {
return this.each(function () {
$(this).removeClass().addClass(val);
});
};
次に、次のように使用できます
$("selector").removeClassExcept("aa dd");
例を次に示します: http://jsfiddle.net/9xhND/
アップデート
Brad Christie のロジックを使用すると、この更新では元のクラスのみが保持され、新しいクラスは追加されません。 http://jsfiddle.net/9xhND/1/
jQuery.fn.removeClassExcept = function (val) {
return this.each(function (index, el) {
var keep = val.split(" "), // list we'd like to keep
reAdd = [], // ones that should be re-added if found
$el = $(el); // element we're working on
// look for which we re-add (based on them already existing)
for (var c = 0; c < keep.length; c++){
if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
}
// drop all, and only add those confirmed as existing
$el
.removeClass() // remove existing classes
.addClass(reAdd.join(' ')); // re-add the confirmed ones
});
};
.removeClass()
パラメータとして、実際に削除するクラスを返す関数を受け入れます。
それで
$('div').removeClass(function(i, class){
// variable class hold the current value of the class attribute
var list = class.split(' '); // we create an array with the classes
return list.filter(function(val){ // here we remove the classes we want to keep
return (val != 'aa' && val != 'dd');
}).join(' '); // and return that list as a string which indicates the classes to be removed..
});
jQueryは実際にはremoveClassメソッドにコールバックパラメーターを提供するため、単純なjavascript正規表現を使用して、削除したくないクラスを除くすべてのクラスを返すことができます。
$('#myDiv').removeClass(function() {
return $(this).attr('class').replace(/aa|bb/g, '');
});
このようにして、クラス「aa」と「bb」がまだ存在しない場合は追加しません。
ここで実際の動作を確認できます:http://jsfiddle.net/sr86u/3/
すべてを削除して、必要なものを追加し直すことができます。
$('#divID').removeClass()
.addClass('aa dd'); // add multiple classes by separating with space
注:removeClass()
特定のクラス名を指定せずに呼び出すと、すべてのクラスが削除されます。
それを行う1つの方法は、すべてのクラスを保持したいクラスで上書きすることです。したがって、div の ID が「myDiv」の場合は、次のようにできます。
$('#myDiv').attr('class', 'aa dd');
保持したいクラスがわかっている場合は、それらを再度追加できます(他の人がすでに示したように)。
ただし、これらのクラスが既に適用されているかどうかは不明であるため、さらに一歩進めます。
var keep = ['aa','bb'], // list we'd like to keep
reAdd = [], // ones that should be re-added if found
$el = = $(el); // element we're working on
// look for which we re-add (based on them already existing)
for (var c = 0; c < keep.length; c++){
if ($el.hasClass(keep[c])) reAdd.push(keep[c]);
}
// drop all, and only add those confirmed as existing
$el
.removeClass() // remove existing classes
.addClass(reAdd.join(' ')); // re-add the confirmed ones