Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching class between two elements using jQuery

Tags:

jquery

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?

like image 766
peirix Avatar asked Dec 12 '25 04:12

peirix


1 Answers

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);
like image 84
meagar Avatar answered Dec 14 '25 20:12

meagar