Javascript – jquery remove matching classes

javascriptjquery

I have a list of stuff with thing like

                    <ul>
                        <li>
                            <div class="pack1 active1"><span>$3.99</span></div>
                        </li>
                        <li>
                            <div class="pack2"><span>$5.99</span></div>
                        </li>
                        <li>
                            <div class="pack3 active3"><div id="ribbon"><span>40</span></div><span>$6.99</span></div>
                        </li>
                        <li>
                            <div class="pack4"><span>$10.99</span></div>
                        </li>
                        <li>
                            <div class="pack5"><span>$259.99</span></div>
                        </li>
                    </ul>

and I want to remove all the active* classes on click. I've tried to do something like $('*[class^="active"]').removeClass() but that isn't working

Any help?

Best Answer

OK, I tested it and this definitely works even if there are more than one "active-something" classes assigned to one element:

$('[class*="active"]').removeClass(function(i, c) {
  return c.match(/active\d+/g).join(" ");
});

The 'i' is the index of matched element and 'c' is the value of the class attribute for the matched element so you don't need to "ask" for it again. $("...").removeClass() can remove all classes specified by the value so if there are more than one "active-something" classes assigned to this element we're returning all the occurences from the call to match (using the 'g' option at the end of the regular expression) and then concatenating it so that the actual removeClass function then can process it accordingly.