I’m quite new to JS and I would like to create a custom (unique) function in order to add/remove CSS classes to/from HTML elements.
I mean something like this:
const myFunction = (element, action, cls) => element.classList.action(cls);
Where:
- element is the HTML element;
- action is “add” or “remove”;
- cls is the CSS class(es).
But, when I invoke
myFunction(document.querySelector("main"), add, "myClass");
I get the following error:
Uncaught ReferenceError: add is not defined
While, when I invoke
myFunction(document.querySelector("main"), "add", "myClass");
I get the following error:
Uncaught TypeError: element.classList.action is not a function
The reason of those errors is quite clear.
But, is there a way to fix them?. Or do I have unavoidably to create two different functions: one to add and one to remove CSS classes?