Adding or removing classes with pure JavaScript

While JQuery makes it possible to easily add and remove classes, it is almost equally easy with pure JavaScript. First you need to create a reference to the element, this can be done via the unique id of the element (defined with the id attribute). In JavaScript we may use document.getElementById() for this purpose:

To remove the class, you can simply set it back to its original state. That is, if there were any classes already present, you will need to list those. For example:

e.className = "some_class another_class";

When to use pure JavaScript instead of JQuery

The pure JavaScript way might be better in cases were you do not need the full functionality of a library. Sometimes you might want to avoid pure JavaScript solutions, as it can be difficult to make it work in all browsers. However, in this case it should be fairly safe. Try it out for yourself.

The only disadvantage of the pure JavaScript solution mentioned above, is that it requires space in it to separate from potential existing classes on the element. Beginners might find confusing, but it makes sense when you think about it.

There is also another way of doing it, but it is not supported in Internet Explorer 10. The browser is,
however, very old (from 2012), so we should not support it. Tell users to switch to another browser, or upgrade their systems.