Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all classes that begin with a certain string

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*"); 
like image 867
Brad Avatar asked Sep 11 '08 22:09

Brad


People also ask

How do I get rid of all classes?

To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.


1 Answers

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(); 
like image 189
Kabir Sarin Avatar answered Oct 15 '22 06:10

Kabir Sarin