jQuery replace one class with another

To do this efficiently using jQuery, you can chain it like so:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you’re targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

For modern browsers (See this to see which browsers I’m calling modern)

(assuming one element with class theClassThatsThereNow)

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYour

Leave a Comment