-
-
Save jakubp/2881585 to your computer and use it in GitHub Desktop.
// Remove classes that have given prefix | |
// Example: | |
// You have an element with classes "apple juiceSmall juiceBig banana" | |
// You run: | |
// $elem.removeClassPrefix('juice'); | |
// The resulting classes are "apple banana" | |
// NOTE: discussion of implementation techniques for this, including why simple RegExp with word boundaries isn't correct: | |
// http://stackoverflow.com/questions/57812/jquery-remove-all-classes-that-begin-with-a-certain-string#comment14232343_58533 | |
(function ( $ ) { | |
$.fn.removeClassPrefix = function (prefix) { | |
this.each( function ( i, it ) { | |
var classes = it.className.split(" ").map(function (item) { | |
return item.indexOf(prefix) === 0 ? "" : item; | |
}); | |
it.className = classes.join(" "); | |
}); | |
return this; | |
} | |
})( jQuery ); |
What IE version, and what error, and how are you using it...? :) Please create e.g. a fiddle http://jsfiddle.net/ so I have something to respond to really...
Not sure, but I believe the problem may be that the map function is not supported in earlier versions of IE? Changing it to something like this should work:
var classes = it.className.split(" ");
$.map(classes, function(item) { ...
Hi Sarink, i think you are right...but some how i found different code which is little bit lengthy but working fine in all the versions of IE and chrome...... Below code i am using,have a look:-
$.fn.removeClassPrefix = (function(oldRemoveClass){
return function(){
// Turn arguments into a true array
var args = Array.prototype.slice.call(arguments);
var class_list = args[0];
var classes = class_list.split(' ');
var new_class_list = [];
var get_rid = [];
var $t = $(this);
for(var i = 0, clen = classes.length; i < clen; i++){
if(classes[i].indexOf('') !== -1){
var c_stripped = classes[i].replace('_', '');
$t.filter('[class*="' + c_stripped + '"]').each(function(){
var cl = this.className.split(' ');
for(var j = 0, jlen = cl.length; j < jlen; j++){
if(cl[j].indexOf(c_stripped) !== -1){
get_rid.push(cl[j]);
}
};
});
}
else {
new_class_list.push(classes[i]);
}
}
args[0] = $.merge(new_class_list, get_rid).join(' ');
return _oldRemoveClass.apply(this, args);
};
})($.fn.removeClass);
This is awesome and does what I need.... I did notice that in Safari at least, for some reason extra spaces were being appended in the string as the class changed. I changed line 18 to:
it.className = $.trim(classes.join(" "));
And that seems to have resolved the issue.
I am almost sure, that problem with IE occured because of "each" function, earlier versions of IE doesn't support it. The workaround is to use normalized jQuery
above code is giving error in IE. please suggest the solution...