Is there a way to acplish the following in one line?
item.removeClass('oldClass')
item.addClass('newClass')
Something like replaceClass
?
Is there a way to acplish the following in one line?
item.removeClass('oldClass')
item.addClass('newClass')
Something like replaceClass
?
5 Answers
Reset to default 11With 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./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 would like to try using jquery-ui
switchClass('oldClass', 'newClass');
item.removeClass('oldClass').addClass('newClass')
$('.theclassthatstherenow').addClass('newclasswithyourstyles');
$('.theclassthatstherenow').removeClass('theclassthatstherenow');
To do this in one line using jQuery, please use given code.
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('.oldclass').addClass('newclass').removeClass('oldclass');
</script>