Utilizing JavaScript to alter the style of an element results in a highly specific rule that is challenging to identify and undo, particularly when dealing with multiple style effects. It becomes less flexible as well – for example, if you desire both a border and a background, the workload essentially doubles.
Typically, it is much more advantageous from a maintenance standpoint, flexibility perspective, and separation-of-concerns ideology to refrain from directly modifying an element's style. Instead, opt to change its class and let CSS handle the rest.
For instance, if I wish to implement a new border and background style, I would define a corresponding class in my CSS:
.highlight
{
border: 1px solid black;
background: white;
}
Subsequently, I can apply this class to the relevant element like so:
document.getElementById('myElementId').className += " highlight"; //note the space
In practice, it would be advisable to encapsulate this class modification within a more comprehensive wrapper to avoid double assignment and facilitate removal. Nonetheless, the concept remains straightforward – changing the effect of "highlight" at a single location is now effortless, ensuring normal cascading behavior and simplifying the process of verifying its presence compared to checking specific style attributes.
This approach also contributes significant semantic value. Having self-explanatory code is undeniably beneficial.