tags:

views:

26

answers:

1

I have the following set up:

<div class="click red"></div>
<div class="click green"></div>
<div class="click blue"></div>

and when "click" is clicked I want to add the class "load" to the div. I have managed this fine, but "red" "green" and "blue" all have a background image set so I need to remove that class. Now, I know how to do this the sloppy way, I take the class for the dib "click blue" (as returned by jquery) and then strip out what I need and replace it but this is incredibly sloppy and I can't see it being the proper method.

What's the proper way to approach this? I need to remove the second class from the div and replace it with the class "load". Is there some sort of method for calling each class individually, .attr("class")[2]?

+2  A: 

If you know the class is "click", you can set the class, rather then add/removing it, like this:

$('div').attr('class', 'click load');

If you know the classes (not sure if this is a simplified example) you want to remove, you can do this:

$("div").removeClass('red green blue').addClass('load');

Edit: Based on comments - You can store the class using $.data() and grab it later to restore it after the load, like this:

In your click function:

$.data(this, 'class', $(this).attr('class')); //store the original class
$(this).attr('class', 'click load');          //set loading class

Then to restore it later:

$(this).attr('class', $.data(this, 'class')); //restore orignal class
Nick Craver
I need to retain the latter class for reverting after though. I guess the method would be to create a variable containing the current class, then replace it with "click load" and then revert back to the variable? Sounds workable, thanks!
@user265331 - Ah one sec, I'll update on how to do that :)
Nick Craver
It's fine, I know how, I was just asking about the theory :-) I'll tick your answer whenever the site lets me (10 minute wait). Thanks!
@user265331 - Alrighty :) I added it anyway, in case anyone in the future finds this useful as well.
Nick Craver