JavaScript Style Modification
A webpage without JavaScript styling is static. By dynamically altering styles via the Document Object Model (DOM), you bring interactivity to life—think dropdown menus, dark mode toggles, and modal popups.
Inline Styles: The .style Object
Every DOM element has a style object representing its inline CSS attributes. Accessing it is simple: element.style.color = 'red';. However, there is a critical syntax shift. Because JavaScript parses hyphens as subtraction operators, any CSS property containing a hyphen must be written in camelCase. For example, background-color becomes backgroundColor, and z-index becomes zIndex.
Note on Specificity: Styles applied this way map directly to the HTML style="..." attribute. This means they have a very high CSS specificity, overriding classes and IDs in your external stylesheets. Because of this overriding nature, directly modifying .style should be used sparingly—usually for dynamically calculated values (like coordinates for drag-and-drop).
classList: The Modern Standard
Instead of modifying individual CSS rules, the best practice is to pre-define your styles in CSS classes, and then use JavaScript to add or remove those classes. Enter the classList API.
element.classList.add('className'): Adds the specified class.element.classList.remove('className'): Removes the specified class.element.classList.toggle('className'): Adds the class if it doesn't exist, removes it if it does. This is incredibly powerful for binary states like "open/closed" or "dark/light".
Computed Styles
If you try to read element.style.color on an element styled by an external stylesheet, it will return an empty string. The .style object only reads inline styles. To find out the actual rendered style of an element, you must use window.getComputedStyle(element). This returns an object containing the final, calculated CSS values after the browser has applied all stylesheets.
View Performance Tips+
When dealing with numerous style changes, modifying className or using classList.add/remove is generally faster and triggers fewer browser repaints than altering multiple .style properties one by one. Furthermore, if you completely want to overwrite all inline styles as a raw string, you can use element.style.cssText = "color: red; padding: 10px;".
