You can pass a removeClass function that returns a list of classes that you want to remove. In this function, you can check whether each of the classes will start with bg, and then, if so, add it to the list of classes that you want to remove.
$("#buttoncolors").on("change", function () { var valcolor = $("#buttoncolors").val(); $("#buttonstyle").removeClass(function (index, classNames) { var current_classes = classNames.split(" "),
Demo: http://codepen.io/iblamefish/pen/EhCaH
Bonus
You can clear the code using the name function rather than anonymous for the callback so you can use it more than once.
// name the function function removeColorClasses (index, classNames) { var current_classes = classNames.split(" "), // change the list into an array classes_to_remove = []; // array of classes which are to be removed $.each(current_classes, function (index, class_name) { // if the classname begins with bg add it to the classes_to_remove array if (/bg.*/.test(class_name)) { classes_to_remove.push(class_name); } }); // turn the array back into a string return classes_to_remove.join(" "); }
Then you can use this function again and again, passing its name where you usually write function () { ... }
// code that the dropdown box uses $("#buttoncolors").on("change", function () { var valcolor = $("#buttoncolors").val(); $("#buttonstyle").removeClass(removeColorClasses); $("#buttonstyle").addClass(valcolor); }); // another example: add a new button to remove all classes using the same function $("#buttonclear").on("click", function () { $("#buttonstyle").removeClass(removeColorClasses); });
source share