I have a line of code in JavaScript, using prototype, that is run several times per second. This line of code, depending on the state of some variables, would ensure that certain element has or has not a class.
My question is, should I blindly add or remove the class or should I check for it first? Should I have this code:
if (!element.hasClassName("overtime")) {
element.addClassName("overtime");
}
if (element2.hasClassName("overtime")) {
element2.removeClassName("overtime");
}
or is it fine to just have:
element.addClassName("overtime");
element2.removeClassName("overtime");
My reasoning is that adding and removing may be more expensive methods that even though the change happens super fast, may modify the DOM, leading to flakiness or exacerbate a memory leak or something like that.