Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all instances of a class in javascript/jquery?

I have this class called .m-active that is used multiple times throughout my HTML.

Basically what I want to do is remove all instances of that class when a user clicks on an image (which does not have the m-active class) and add the m-active class to that image.

For instance in a Backgrid row you might have a click handler as follows:

"click": function () {     this.$el.addClass('m-active'); } 

But you also want to remove that class from any rows to which it was previously added, so that only one row at a time has the .m-active class

Does anyone know how this can be done in javascript/jquery?

like image 337
jdc987 Avatar asked Jul 15 '13 19:07

jdc987


People also ask

What is removeClass in jQuery?

The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.

How do you remove an active class?

removeClass() Method. This method removes one or more class names from the selected elements. If no parameter is specified in the removeClass() method, it will remove all class names from the selected elements.


2 Answers

With jQuery:

$('.m-active').removeClass('m-active'); 

Explanation:

  • Calling $('.m-active') selects all elements from the document that contain class m-active
  • Whatever you chain after this selector gets applied to all selected elements
  • Chaining the call with removeClass('m-active') removes class m-active from all of the selected elements

For documentation on this specific method, see: http://api.jquery.com/removeClass/

Getting grasp of the whole selector thing with jQuery is challenging at first, but once you get it, you see everything in very different light. I encourage you to take a look into some good jQuery tutorials. I personally recommend checking out Codeacademy's jQuery track: http://www.codecademy.com/tracks/jquery

like image 96
jsalonen Avatar answered Oct 03 '22 01:10

jsalonen


all answers point to remove the class from the DOM element. But if you are asking to remove the element itself you can user .remove() jquery method

$('.m-active').remove(); 

JQuery Remove Docs

like image 39
Alireza Avatar answered Oct 03 '22 01:10

Alireza