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*");
To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.
A regex splitting on word boundary \b
isn't the best solution for this:
var prefix = "prefix"; var classes = el.className.split(" ").filter(function(c) { return c.lastIndexOf(prefix, 0) !== 0; }); el.className = classes.join(" ").trim();
or as a jQuery mixin:
$.fn.removeClassPrefix = function(prefix) { this.each(function(i, el) { var classes = el.className.split(" ").filter(function(c) { return c.lastIndexOf(prefix, 0) !== 0; }); el.className = $.trim(classes.join(" ")); }); return this; };
2018 ES6 Update:
const prefix = "prefix"; const classes = el.className.split(" ").filter(c => !c.startsWith(prefix)); el.className = classes.join(" ").trim();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With