In my previous ES6 article, I introduced you to the classList property that’s newly available for use by the JavaScript development community. As you may know, this classList property offers a few new, extremely easy-to-use methods that allow JS developers to manipulate an element’s list of class names. I wish that this newer type of functionality using the classList property had been accomplished and integrated into browsers a long time ago as it would have stopped many developers from pulling their hair out. As they say – better late than never.
We all know a handful of coders that would implement the unneeded inclusion of jQuery into their web project just to accomplish class-related tasks, such as using the removeClass() method in jQuery. This can be eliminated and your future web project output file sizes may decrease due to no longer needing the use of the jQuery library. This is yet another positive change that ES6 brings. The new classList property offers us the use of the remove() method, allowing us to easily remove a class from an element.
About the classList.remove() method
Adding a class to an element was very easy to accomplish in our previous tutorial, and removing a class from an element will be just as simple. Developers everywhere can rejoice at the ease of use when it comes to the actual syntax and the simplicity of the new classList property. The classList property has saved coders so much time messing with lines and lines of code that are unnecessary since ES6 was released. Along with the classList.add() method, the new classList.remove() method is very widely used; both are the most popularĀ of the classList methods.
How to use the classList.remove() method in ES6
The remove method for classList is very simple to use. You’ll be removing classes from elements in no time!
Here’s an example for you. Let’s say we have an element with the id of “container”. It has classes consisting of “list-item” and “first”.
<div id="container" class="list-item first"></div>
We want to remove the class “first” from our container. In JavaScript, we need to define a variable for the container.
let el = document.getElementById('container');
Now we can manipulate the classes. With the code below, you can use the ES6 remove() method to easily remove that class name from the element as shown below.
el.classList.remove('first');