Home >Web Front-end >CSS Tutorial >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();
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();
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!