Is there a way to accomplish the following in one line?
item.removeClass('oldClass')
item.addClass('newClass')
Something like replaceClass ?
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:
toggleClass().If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With