I have two elements with a class name each. And on some event I'd like them to switch class.
So basically I'd like to do something like this:
$("#div1").switchClassWith("#div2");
<div id="div1" class="someStylingClass">...content...</div>
<div id="div2" class="someOtherClass">...content...</div>
And this would result in #div1 having someOtherClass as its class name, and #div2 have someStylingClass... Any suggestions?
You could use toggleClass():
$('#div1,#div2').toggleClass('someStylingClass someOtherClass');
Assuming you start with the example you posted, where each element has one class or the other (but not both) then this will work as expected.
If you need to swap the classes without knowing what classes you're swapping, you can do:
var $div1 = $('#div1'), $div2 = $('#div2'), tmpClass = $div1.attr('class');
$div1.attr('class', $div2.attr('class'));
$div2.attr('class', tmpClass);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With