I have a select field with different values :
- africa
- europe
- america
- asia
- oceania
When selecting a value, I want to add a css class to a specific div, the name of the css class being the value selected. Easy enough :
$(document).on("change", "[data-name='continent'] select", function () {
var continent = $('[data-name="continent"] select').val();
$("#mydiv").addClass(continent);
});
This works fine, but there is a problem : if I change the select field value, the previous classes will not be removed. I can't do :
$("#mydiv").removeClass().addClass(continent);
Because #mydiv already has other important classes. I could do :
$("#mydiv").removeClass('africa').removeClass('europe').removeClass('america').removeClass('asia').removeClass('oceania').addClass(continent);
But in reality I have more than just 5 options and they might change in the future; I'd rather keep things flexible. And more than anything, i want to learn javascript. Is there any way to remove all the classes that are values of the select field ?