Reputation: 110093
Is there a way to accomplish the following in one line?
item.removeClass('oldClass')
item.addClass('newClass')
Something like replaceClass
?
Upvotes: 2
Views: 13816
Reputation: 892
To do this in one line using jQuery, please use given code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('.oldclass').addClass('newclass').removeClass('oldclass');
</script>
Upvotes: 0
Reputation: 1
$('.theclassthatstherenow').addClass('newclasswithyourstyles');
$('.theclassthatstherenow').removeClass('theclassthatstherenow');
Upvotes: 0
Reputation: 253308
With no further context, I'd suggest:
item.toggleClass('oldClass newClass');
If, however, you really want a replaceClass()
method (though I can't see what it might offer, functionally):
(function($) {
$.fn.replaceClass = function(classes) {
var allClasses = classes.split(/\s+/).slice(0, 2);
return this.each(function() {
$(this).toggleClass(allClasses.join(' '));
});
};
})(jQuery);
$('div').replaceClass('oldClass newClass');
.oldClass {
color: #f00;
}
.newClass {
color: #0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="oldClass">This element starts with the class "oldClass"</div>
<div class="newClass">This element starts with the class "newClass"</div>
References:
Upvotes: 11
Reputation: 3305
If you would like to try using jquery-ui
switchClass('oldClass', 'newClass');
Upvotes: 1