Reputation: 4693
I have several buttons. When clicked I would like to remove all classes from my text field.
Currently this is what I have, but the code is not optimized.
var maintextarea = $('.myTextArea');
$('#styleBtn1').click(function(){
maintextarea.removeClass('fromStyleBtn2 fromStyleBtn3');
maintextarea.addClass('fromStyleBtn1');
return false;
});
$('#styleBtn2').click(function(){
maintextarea.removeClass('fromStyleBtn1 fromStyleBtn3');
maintextarea.addClass('fromStyleBtn2');
return false;
});
$('#styleBtn3').click(function(){
maintextarea.removeClass('fromStyleBtn1 fromStyleBtn2');
maintextarea.addClass('fromStyleBtn3');
return false;
});
Question: How can I rewrite the removeClass
portion so that when a button is clicked all previous classes will be nulled and my class gets added?
Upvotes: 2
Views: 2561
Reputation: 218722
You can simply using the method chaining
maintextarea.removeClass().addClass('fromStyleBtn1');
calling removeClass() without any parameter will remove all classes.
EDIT : Your entire code can be replaced like this generic form.. Assuming your class name will always in the format "from"+elementID. (Ex : fromStyleBtn2)
var maintextarea = $('.myTextArea');
$('.fromStyleBtn1,.fromStyleBtn2,.fromStyleBtn3').click(function(){
var item=$(this);
var newClassName="from"+item.attr("id");
maintextarea.removeClass().addClass(newClassName);
return false;
});
Upvotes: 1
Reputation: 24063
You can override the functionallity of removeClass like this:
$(function() {
var originalRemoveClass=$.fn.removeClass;
$.fn.extend({
removeClass:function(toRemove, toAdd) {
originalRemoveClass.call(this, toRemove);
this.addClass(toAdd);
}
});
});
you can see an example here: http://jsfiddle.net/NuGdM/1/
Another option is to create your plugin that do that (if you need an example - ask me).
Good Luck!
Upvotes: 1
Reputation: 976
If you truly want to remove the class attribute instead of some of the attribute's values use removeAttr().
Upvotes: 1
Reputation: 1502
Here you go, directly from the jQuery documentation for .removeClass():
To replace all existing classes with another class, we can use
.attr('class', 'newClass')
Upvotes: 1