Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace class in jQuery

Is there a way to accomplish the following in one line?

item.removeClass('oldClass')
item.addClass('newClass')

Something like replaceClass ?

like image 232
David542 Avatar asked Mar 14 '26 02:03

David542


1 Answers

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().
like image 103
David Thomas Avatar answered Mar 17 '26 02:03

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!