How can I set multiple CSS styles in JavaScript?
To quickly style an element with multiple properties at once, use Object.assign() by assigning an object containing the desired CSS properties to element.style
:
For applying more than one style using a string, take advantage of cssText
:
Keep in mind it overwrites existing styles, thus handle with care!
Style with Parameter Objects
A reusable styling strategy involves creating a function that accepts a parameter object and an element, applying the styles dynamically:
The function acts as the fitting room where styles are tried on the element.
Sequential Style Updates, No Overwrite!
When overwriting is not an option, iterate over properties to keep existing styles intact:
Selectively updating ensures only your chosen properties get a new look, while the rest stay unfazed.
Improve cssText
readability with Template Literals
Using template literals, you can keep cssText
readable and avoid the pesky +
concatenation:
This method helps when your CSS values are stored in variables and you need a dynamic way to inject those to your styles.
Preventing Overwrites
With cssText
, always ensure to append instead of overwrite important existing styles:
Appending to cssText
ensures the element's existing styles remain unaltered.
Picking Elements Savvily
A modern approach to selecting elements for applying styles is the versatile querySelector
:
This technique is your best bet for complex selectors and multiple elements targeted by a single class.
Efficient Performance, More Power!
Scope to avoid unnecessary DOM repaints and reflows by batching style updates. Instead of one property at a time, use cssText
, Object.assign
or parameters object to set multiple styles at once.
Was this article helpful?