Barrie Reader
Barrie Reader

Reputation: 10713

Can I remove just the last added class from an element with jQuery

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...
});

Upvotes: 2

Views: 2774

Answers (3)

Tim Down
Tim Down

Reputation: 324507

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+)?$/, "");
});

Upvotes: 2

B-Scan
B-Scan

Reputation: 306

Something like:

$('#chuckPalahniuk').click(function() {
    $(this).removeClass($(this).attr('class').split(/\s+/).pop());
});

Upvotes: 1

fcalderan
fcalderan

Reputation:

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

Upvotes: 4

Related Questions