3

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?

peirix
  • 36,512
  • 23
  • 96
  • 126
  • Do you know what these classes are ahead of time, or could they be anything? – Nick Craver Aug 25 '10 at 19:02
  • suggestion: the example looks more like a swapClasses(div1, div2) than div1.switchClassWith(div2) – Rahul Aug 25 '10 at 19:04
  • @Nick: Yeah, I know what the class names are going to be, so I was just looking for something easier than creating a function, which would have to create temp variables and such... – peirix Aug 25 '10 at 20:09

4 Answers4

11

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);
user229044
  • 232,980
  • 40
  • 330
  • 338
1
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
  • 1,974
  • 2
  • 17
  • 26
1

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
  • 1,866
  • 17
  • 32
0

jQuery UI switchClass ?