Reputation: 37741
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?
Upvotes: 3
Views: 4932
Reputation: 239290
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);
Upvotes: 11
Reputation: 1876
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
}
Upvotes: 1
Reputation: 1984
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'));
Upvotes: 1