contentand some buttons ...">

JQuery - delete a class located in an array

I have a div object

<div class="class1 classA classB class2"> content </div> 

and some buttons

 <button id="numbers">clickme N </button> <button id="alphas">clickme A </button> 

The code should perform this function:

 <script> var classesN = [class1, class2, class3]; var classesAlpha = [classA, classB, classC]; $('#alphas').click(function() { $('div').removeClass(all classes that are in the classesAlpha array); }); $('#numbers').click(function() { $('div').removeClass(all classes that are in the classesN array); }) </script> 

Thanks for any suggestion and I hope you enjoy the question :)

+6
source share
3 answers
 var classesN = ["class1", "class2", "class3"]; var classesAlpha = ["classA", "classB", "classC"]; $('#alphas').click(function() { var $div = $('div'); $.each(classesAlpha, function(i, v){ $div.removeClass(v); }); }); 

Demo

+8
source

.removeClass ([className]) : classNameOne or more classes, separated by spaces , that must be removed from the class attribute of each matched element.

So, attach all the classes you want to remove into a list separated by a space.

 var classesN = [class1, class2, class3]; var classesAlpha = [classA, classB, classC]; $('#alphas').click(function() { $('div').removeClass(classesAlpha.join(' ')); }); $('#numbers').click(function() { $('div').removeClass(classesN.join(' ')); }); 
+13
source

Or maybe without the array and join () functions. you only need to assign classes to a variable

 var classesN = "class1 class2 class3"; var classesAlpha = "classA classB classC"; $('#alphas').click(function() { $('div').removeClass(classesAlpha); }); $('#numbers').click(function() { $('div').removeClass(classesN); }); 
+1
source

Source: https://habr.com/ru/post/919964/


All Articles