Removing a class from an HTML-Element with JavaScript is easy enough. You could use jQuery for it by calling
|
|
or, just as simple, go vanilla with:
|
|
But what if you wanted to remove all classes starting with a prefix? Assume we have a DOM-Node like this:
|
|
We want to remove all the classes starting with “test-”, how do we achieve that?
Not even jQuery has a straight-forward answer to that question and doing it with pure JavaScript is even more difficult - or is it? I came up with a nice little function that does just that.
The Magic Of Regular Expressions
|
|
It takes the node and the prefix for the classes you want removed. Behold the power of RegEx! The query I constructed basically checks for the prefix followed by any character except whitespaces ([^ ]*) followed by one or more whitespaces ([ ]?).
An Example
Here’s how that changes the classList:
|
|
Conclusion
There you go! We have a simple yet effective to remove classes by prefix without the need for third-party libraries.