Checking classList with contains if a class exists before add or remove?

Explicitly checking is pointless. It is a waste of time and bloats your code.

Those checks are effectively built-in to the add and remove class methods.

If you try to add a class that the element is already a member of, then classList.add will ignore it.

If you try to remove a class that the element isn't a member of, then classList.remove will do nothing.


Both the ways are correct there is no sense that it is important but in some cases you may need to use .contains() totally depends on you situation.

But globally its not important you can directly remove the class. If class exists then code will work otherwise not.

Tags:

Javascript