user1047517 user1047517 - 6 months ago 89
Javascript Question

jQuery replace one class with another

I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:

$('.corpo_buttons_asia').click(function() {
$('.info').css('visibility', 'hidden');
$('.info2').css('visibility', 'visible');
$(this).css('z-index', '20');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_global').css('color', '#383838');
});

$('.corpo_buttons_global').click(function() {
$('.info').css('visibility', 'visible');
$('.info2').css('visibility', 'hidden');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_asia').css('z-index', '2');
$('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_asia').css('color', '#383838');
});




So instead of using .css() all the time I can create another class and just replace it with jQuery.

Thanks.

Answer

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:

$('.theclassthatstherenow').addClass('newclasswithyourstyles');
$('.theclassthatstherenow').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*/, ' newclasswithyourstylerules ');
Comments