tags:

views:

40

answers:

4

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?

+3  A: 

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);
meagar
`.toggleClass('someStylingClass someOtherClass')` :)
Nick Craver
@Nick, nice one :)
RC
@Nick Thanks, modified answer
meagar
It's better to cache the div1 and div2 selection. In this case you've selected both of the 2 times instead of only once.
IgalSt
I knew there had to be some sweet, sweet, one-liner to fix this!
peirix
A: 

jQuery UI switchClass ?

RC
A: 
function SwitchClass(a,b){
  var aClass = a.attr('class');
  var bClass = b.attr('class');
  a.removeClass(aClass).addClass(bClass);
  b.removeClass(bClass).addClass(aClass);
}


SwitchClass($('div1'),$('div2'));
IgalSt
A: 

pseudo code



function swapClasses(element1, element2)
{
   class1List1 = getClassList(element1)
   classList2 = getClassList(element2)

   for class in classList1
   {
       element2.addClass(class)
   }

   //similarly for element1
}

function getClassList(element)
{
   //refer to http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery
}


Rahul