David542
David542

Reputation: 110093

Replace class in jQuery

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

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

Something like replaceClass ?

Upvotes: 2

Views: 13816

Answers (5)

anilam
anilam

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

Lapiz
Lapiz

Reputation: 1

$('.theclassthatstherenow').addClass('newclasswithyourstyles');
$('.theclassthatstherenow').removeClass('theclassthatstherenow');

Upvotes: 0

David Thomas
David Thomas

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

Liam Schauerman
Liam Schauerman

Reputation: 841

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

Upvotes: 1

Lumi Lu
Lumi Lu

Reputation: 3305

If you would like to try using jquery-ui

switchClass('oldClass', 'newClass'); 

Upvotes: 1

Related Questions