Remove all classes that begin with a certain string

css, javascript, jquery

Solution

With jQuery, the actual DOM element is at index zero, this should work

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');

Problem

I have a div with `id="a"` that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works: ``` $("#a").removeClass("bg*"); ```

Original source

Related problems