Home >Web Front-end >CSS Tutorial >How to Remove Classes with a Specific Prefix in JavaScript?

How to Remove Classes with a Specific Prefix in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 02:19:101093browse

How to Remove Classes with a Specific Prefix in JavaScript?

How to Remove Classes with Specific Prefix

Problem Statement

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.

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn