Removing a class from an HTML-Element with JavaScript is easy enough. You could use jQuery for it by calling

Copy to Clipboard

or, just as simple, go vanilla with:

Copy to Clipboard

But what if you wanted to remove all classes starting with a prefix? Assume we have a DOM-Node like this:

Copy to Clipboard

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

Copy to Clipboard

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:

Copy to Clipboard

Conclusion

There you go! We have a simple yet effective to remove classes by prefix without the need for third-party libraries.