How to check classList with contains if a class exists before add or remove with JavaScript?

Sometimes, we want to check classList with contains if a class exists before add or remove with JavaScript.

In this article, we’ll look at how to check classList with contains if a class exists before add or remove with JavaScript.

How to check classList with contains if a class exists before add or remove with JavaScript?

To check classList with contains if a class exists before add or remove with JavaScript, we can just call classList.add or classList.remove without doing the check.

For instance, we write:

<p>
  foo
</p>

to add a p element.

Then we write:

const element = document.querySelector('p')
element.classList.remove('info');
element.classList.add('hint');

We select the p element with document.querySelector.

Then we call element.classList.remove to remove the info class.

And call element.classList.add to add the hint class.

Conclusion

To check classList with contains if a class exists before add or remove with JavaScript, we can just call classList.add or classList.remove without doing the check.