<p>I have a div with <code>id="a"</code> 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:</p>

<pre><code>$("#a").removeClass("bg*");
</code></pre>

[{'answer_id': 57819, 'author': 'Prestaul', 'author_id': 5628, 'author_profile': 'https://Stackoverflow.com/users/5628', 'pm_score': 4, 'selected': False, 'text': '<p>You don\'t need any jQuery specific code to handle this.  Just use a RegExp to replace them:</p>\n\n<pre><code>$("#a").className = $("#a").className.replace(/\\bbg.*?\\b/g, \'\');\n</code></pre>\n\n<p>You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:</p>\n\n<pre><code>function removeClassByPrefix(el, prefix) {\n    var regx = new RegExp(\'\\\\b\' + prefix + \'.*?\\\\b\', \'g\');\n    el.className = el.className.replace(regx, \'\');\n    return el;\n}\n</code></pre>\n'}, {'answer_id': 58097, 'author': 'Brad', 'author_id': 5464, 'author_profile': 'https://Stackoverflow.com/users/5464', 'pm_score': 0, 'selected': False, 'text': '<p>Prestaul\'s answer was helpful, but it didn\'t quite work for me. The jQuery way to select an object by id didn\'t work. I had to use</p>\n\n<pre><code>document.getElementById("a").className\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>$("#a").className\n</code></pre>\n'}, {'answer_id': 58533, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 7, 'selected': True, 'text': "<p>With jQuery, the actual DOM element is at index zero, this should work</p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.*?\\b/g, '');\n</code></pre>\n"}, {'answer_id': 627368, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.mail-archive.com/jquery-en@googlegroups.com/msg03998.html" rel="nofollow noreferrer">http://www.mail-archive.com/jquery-en@googlegroups.com/msg03998.html</a> says:</p>\n\n<p>...and .removeClass() would remove all classes...</p>\n\n<p>It works for me ;)</p>\n\n<p>cheers</p>\n'}, {'answer_id': 3284637, 'author': 'jamland', 'author_id': 344306, 'author_profile': 'https://Stackoverflow.com/users/344306', 'pm_score': 0, 'selected': False, 'text': "<p>I also use hyphen'-' and digits for class name. So my version include '\\d-'</p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className.replace(/\\bbg.\\d-*?\\b/g, '');\n</code></pre>\n"}, {'answer_id': 8624674, 'author': 'Pete B', 'author_id': 263643, 'author_profile': 'https://Stackoverflow.com/users/263643', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve written a simple <a href="https://gist.github.com/1517285" rel="nofollow noreferrer">jQuery plugin - alterClass</a>, that does wildcard class removal. \nWill optionally add classes too.</p>\n\n<pre><code>$( \'#foo\' ).alterClass( \'foo-* bar-*\', \'foobar\' ) \n</code></pre>\n'}, {'answer_id': 10835425, 'author': 'Kabir Sarin', 'author_id': 1181570, 'author_profile': 'https://Stackoverflow.com/users/1181570', 'pm_score': 7, 'selected': False, 'text': '<p>A regex splitting on word boundary <code>\\b</code> isn\'t the best solution for this:</p>\n\n<pre><code>var prefix = "prefix";\nvar classes = el.className.split(" ").filter(function(c) {\n    return c.lastIndexOf(prefix, 0) !== 0;\n});\nel.className = classes.join(" ").trim();\n</code></pre>\n\n<p>or as a jQuery mixin:</p>\n\n<pre><code>$.fn.removeClassPrefix = function(prefix) {\n    this.each(function(i, el) {\n        var classes = el.className.split(" ").filter(function(c) {\n            return c.lastIndexOf(prefix, 0) !== 0;\n        });\n        el.className = $.trim(classes.join(" "));\n    });\n    return this;\n};\n</code></pre>\n\n<p>2018 ES6 Update:</p>\n\n<pre><code>const prefix = "prefix";\nconst classes = el.className.split(" ").filter(c =&gt; !c.startsWith(prefix));\nel.className = classes.join(" ").trim();\n</code></pre>\n'}, {'answer_id': 12635031, 'author': 'Jan.J', 'author_id': 937367, 'author_profile': 'https://Stackoverflow.com/users/937367', 'pm_score': 1, 'selected': False, 'text': "<p>I know it's an old question, but I found out new solution and want to know if it has disadvantages?<br /></p>\n\n<pre><code>$('#a')[0].className = $('#a')[0].className\n                              .replace(/(^|\\s)bg.*?(\\s|$)/g, ' ')\n                              .replace(/\\s\\s+/g, ' ')\n                              .replace(/(^\\s|\\s$)/g, '');\n</code></pre>\n"}, {'answer_id': 13944814, 'author': 'Rob', 'author_id': 1200670, 'author_profile': 'https://Stackoverflow.com/users/1200670', 'pm_score': 0, 'selected': False, 'text': "<pre><code>(function($)\n{\n    return this.each(function()\n    {\n        var classes = $(this).attr('class');\n\n        if(!classes || !regex) return false;\n\n        var classArray = [];\n\n        classes = classes.split(' ');\n\n        for(var i=0, len=classes.length; i&lt;len; i++) if(!classes[i].match(regex)) classArray.push(classes[i]);\n\n        $(this).attr('class', classArray.join(' '));\n    });\n})(jQuery);\n</code></pre>\n"}, {'answer_id': 14855671, 'author': 'majorsk8', 'author_id': 2068678, 'author_profile': 'https://Stackoverflow.com/users/2068678', 'pm_score': -1, 'selected': False, 'text': '<pre><code>$("#element").removeAttr("class").addClass("yourClass");\n</code></pre>\n'}, {'answer_id': 15235183, 'author': 'abernier', 'author_id': 133327, 'author_profile': 'https://Stackoverflow.com/users/133327', 'pm_score': 3, 'selected': False, 'text': '<p>Using <a href="http://api.jquery.com/removeClass/#removeClass-functionindex--class" rel="noreferrer">2nd signature</a> of <code>$.fn.removeClass</code> :</p>\n\n<pre><code>// Considering:\nvar $el = $(\'&lt;div class="  foo-1 a b foo-2 c foo"/&gt;\');\n\nfunction makeRemoveClassHandler(regex) {\n  return function (index, classes) {\n    return classes.split(/\\s+/).filter(function (el) {return regex.test(el);}).join(\' \');\n  }\n}\n\n$el.removeClass(makeRemoveClassHandler(/^foo-/));\n//&gt; [&lt;div class=\u200b"a b c foo"&gt;\u200b&lt;/div&gt;\u200b]\n</code></pre>\n'}, {'answer_id': 19368577, 'author': 'Pawel', 'author_id': 696535, 'author_profile': 'https://Stackoverflow.com/users/696535', 'pm_score': 2, 'selected': False, 'text': '<p>I was looking for solution for exactly the same problem. To remove all classes starting with prefix "fontid_" After reading this article I wrote a small plugin which I\'m using now.</p>\n\n<pre><code>(function ($) {\n        $.fn.removePrefixedClasses = function (prefix) {\n            var classNames = $(this).attr(\'class\').split(\' \'),\n                className,\n                newClassNames = [],\n                i;\n            //loop class names\n            for(i = 0; i &lt; classNames.length; i++) {\n                className = classNames[i];\n                // if prefix not found at the beggining of class name\n                if(className.indexOf(prefix) !== 0) {\n                    newClassNames.push(className);\n                    continue;\n                }\n            }\n            // write new list excluding filtered classNames\n            $(this).attr(\'class\', newClassNames.join(\' \'));\n        };\n    }(fQuery));\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$(\'#elementId\').removePrefixedClasses(\'prefix-of-classes_\');\n</code></pre>\n'}, {'answer_id': 29002847, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:</p>\n\n<pre><code>function removeclasses(controlIndex,classPrefix){\n    var classes = $("#"+controlIndex).attr("class").split(" ");\n    $.each(classes,function(index) {\n        if(classes[index].indexOf(classPrefix)==0) {\n            $("#"+controlIndex).removeClass(classes[index]);\n        }\n    });\n}\n</code></pre>\n\n<p>Now this function can be called from anywhere, onclick of button or from code:</p>\n\n<pre><code>removeclasses("a","bg");\n</code></pre>\n'}, {'answer_id': 44884314, 'author': 'Adam111p', 'author_id': 3058581, 'author_profile': 'https://Stackoverflow.com/users/3058581', 'pm_score': 2, 'selected': False, 'text': "<p>In one line ...\nRemoves all classes that match a regular expression <em>someRegExp</em></p>\n\n<pre><code>$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});\n</code></pre>\n"}, {'answer_id': 53002208, 'author': 'Max', 'author_id': 2944332, 'author_profile': 'https://Stackoverflow.com/users/2944332', 'pm_score': 3, 'selected': False, 'text': "<p>For modern browsers:</p>\n\n<pre><code>let element = $('#a')[0];\nlet cls = 'bg';\n\nelement.classList.remove.apply(element.classList, Array.from(element.classList).filter(v=&gt;v.startsWith(cls)));\n</code></pre>\n"}, {'answer_id': 68063824, 'author': 'danday74', 'author_id': 1205871, 'author_profile': 'https://Stackoverflow.com/users/1205871', 'pm_score': 0, 'selected': False, 'text': "<p>The top answer converted to jQuery for those wanting a jQuery only solution:</p>\n<pre><code>const prefix = 'prefix'\nconst classes = el.attr('class').split(' ').filter(c =&gt; !c.startsWith(prefix))\nel.attr('class', classes.join(' ').trim())\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/57812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5464/']