0

I'm working with a script which ads a class on click of some element. Is there anyway of removing the dynamically created class with on click event, without knowing/declaring its "name"?

So the Jquery part should say something like "on click: remove the class which has been added right now".

The only thing I can come up with is doing the click event and then removing the last class (which should be the dynamic one) which is answered over here LINK . I'm hoping for a better way though..

Community
  • 1
  • 1
Youss
  • 4,196
  • 12
  • 55
  • 109

2 Answers2

1

This is a rather peculiar situation. You might want to re-think your logic or perhaps have some sort of toggle logic attached to the relevant class.

In any case, I would accomplish this by having an additional data-* property containing the last added class name. For example:

// Adding the classname
var className = myClass;
$('#element').addClass(className).data('lastclass',className);

// Removing last added class
var elem = $("#element");
elem.removeClass(elem.data('lastclass'));
Lix
  • 47,311
  • 12
  • 103
  • 131
  • How is this different from the answer for which I put a link in my question, on click: `$(this).removeClass($(this).attr('class').split(/\s+/).pop());` – Youss Apr 21 '13 at 21:10
  • Well I'm not too sure how consistent the ordering is. Especially if there are possibly other scripts running. In my method - there can be only one class name in the `data-lastclass` property. – Lix Apr 21 '13 at 21:12
1

Once a class has been added to an object, there is no way to distinguish it from any other classes that may have been on the object before. So, if you can't modify the click code and can't know anything about the name of the dynamic class, then it's pretty hard to know what to remove.

If you can snapshot the class data before it's clicked and store that on the object as an attribute or using jQuery's .data(), then you can set the state back to that condition.

Or, if you can know anything about the class names that are added in the click, then you can search for those class names and remove just those class names.

jfriend00
  • 683,504
  • 96
  • 985
  • 979