Home >Web Front-end >CSS Tutorial >How to Remove Classes with a Specific Prefix in JavaScript?
You have a div element with an ID of "a" with several classes attached to it, grouped by specific prefixes. You want to remove all classes from a certain group without knowing the specific class names. For example, you aim to eliminate all "bg" prefix classes.
Regex Approach:
var prefix = "bg"; var classes = $("#a").attr("class").split(" ").filter(function(c) { return !(c.match("^" + prefix + "\b")); }); $("#a").attr("class", classes.join(" "));
Loop Approach:
var prefix = "bg"; var classes = $("#a").attr("class").split(" "); for (var i = 0; i < classes.length; i++) { if (classes[i].startsWith(prefix)) { classes.splice(i, 1); i--; } } $("#a").attr("class", classes.join(" "));
jQuery Plugin (ES5):
$.fn.removeClassPrefix = function(prefix) { return this.each(function() { var classes = $(this).attr("class").split(" ").filter(function(c) { return !c.startsWith(prefix); }); $(this).attr("class", classes.join(" ")); }); }; $("#a").removeClassPrefix("bg");
ES6 Alternative (Cleaner Syntax):
const prefix = "bg"; const classes = $("#a").attr("class").split(" ").filter(c => !c.startsWith(prefix)); $("#a").attr("class", classes.join(" "));
The above is the detailed content of How to Remove Classes with a Specific Prefix in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!