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
Release: 2024-11-28 02:19:10
Original
1096 people have browsed it

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(" "));
Copy after login

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(" "));
Copy after login

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");
Copy after login

ES6 Alternative (Cleaner Syntax):

const prefix = "bg";
const classes = $("#a").attr("class").split(" ").filter(c => !c.startsWith(prefix));
$("#a").attr("class", classes.join(" "));
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template