2

Hey guys, the question pretty much asks itself... however, for more clarity:

I have an element called "chuckPalahniuk" and it has classes named "choke", "fightclub" and "haunted".

How could I get it so when I click on the "chuckPalahniuk" element, it removes "haunted" first, then "fightclub" on the second click and "choke" on the third?

also: be aware that the class names are dynamically added.

Cheers. peeeps!

psy.example:

$('#chuckPalahniuk').click(function() {
  $(this).removeLastClassAdded(); //except this function doesn't exist...
});
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
Barrie Reader
  • 10,647
  • 11
  • 71
  • 139
  • 1
    get the class list by http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery and remove last entery – Haim Evgi Nov 11 '10 at 15:07

3 Answers3

4

just save in an array variable c every class you add c.push('yourclass'), then $(this).removeClass(c.pop());

http://www.devguru.com/technologies/ecmascript/quickref/pop.html

2

This will do it and will deal with leading and trailing whitespace, which a split()-based solution will not:

$('#chuckPalahniuk').click(function() {
    this.className = this.className.replace(/(^|\s+)[^\s]+(\s+)?$/, "");
});
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

Something like:

$('#chuckPalahniuk').click(function() {
    $(this).removeClass($(this).attr('class').split(/\s+/).pop());
});
B-Scan
  • 306
  • 3
  • 11