In programming, there is a principle called Seperation of Concerns (or SoC, for short). In a nutshell, SoC means breaking code down to separate, individual components/functions/etc that each have a very specific purpose. By seperating code into individual functions, it makes the code easier to maintain and follow when reviewed, and it allows for much easier expansion to the code base.
Another option is to add an additional class name to each element that you want to select and to prefix it with something like js-. This is a common way that I have seen developers separate their code, and I have, in fact, worked with a fellow developer that prefers to write his code this way. For example, if he wants to have an element that can be dynamically toggled between active and inactive, his code might look something like this:
Enter: HTML custom data attributes!
What the Heck Are Data Attributes?
If you are not familiar with data attributes, they are essentially custom attributes that can be assigned to any HTML element, and they can be called anything you want, and have any value that you want. Custom data attributes will always start with data-. For example, you could have an element that looks like this:
We can even assign custom values to our data attributes, like so:
This looks a little bit messy and requires two different CSS class definitions based on the applied class.
A better approach would be:
I hope that you found this article interesting and helpful, and I encourage you to share your thoughts about this topic in the comments.