Home > Web Front-end > CSS Tutorial > How to Remove Classes with a Specific Prefix from an HTML Element?

How to Remove Classes with a Specific Prefix from an HTML Element?

DDD
Release: 2024-11-26 12:50:09
Original
550 people have browsed it

How to Remove Classes with a Specific Prefix from an HTML Element?

Removing Classes with a Specific Prefix from an HTML Element

In certain scenarios, removing classes from an element based on a predefined prefix becomes necessary. Consider a div with>

The Challenge:

Our objective is to effectively remove all classes with a specific prefix, such as "bg." The attempted solution, $("#a").removeClass("bg*"), fails to achieve the desired outcome.

The Solution:

This task requires a more tailored approach, which involves filtering out and reassigning the class list. A more accurate implementation using JavaScript or jQuery is presented below:

JavaScript:

var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
    return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ").trim();
Copy after login

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

2018 ES6 Update:

const prefix = "prefix";
const classes = el.className.split(" ").filter(c => !c.startsWith(prefix));
el.className = classes.join(" ").trim();
Copy after login

These solutions effectively identify and remove all class names that begin with the specified prefix, allowing for dynamic class management and manipulation.

The above is the detailed content of How to Remove Classes with a Specific Prefix from an HTML Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template