How do you add CSS with JavaScript?
Quickly style an element by targeting it with querySelector
and assigning styles via .style
:
````.cssText``` allows you to apply multiple styles. For setting a single property:
But what if you want to add CSS rules dynamically, based on certain events or conditions? You can create and append a <style>
element to the head
of your document:
Crafting dynamic styles
Multi-line CSS with template literals
In the case of multi-line CSS, ES6 template literals (denoted by backticks `) dramatically improve readability:
Adding styles with DOM manipulation
You can leverage DOM Level 2 CSS with its method insertRule
to insert new rules into an existing stylesheet:
For browsers like Internet Explorer 8 and below that don’t support insertRule
, you must settle for addRule
.
One-liner magic
Here’s a handy one-liner to add CSS:
You can call this function as:
Keeping best practices in mind
Cross-browser compatibility
With dynamic CSS, keep in mind that cross-browser compatibility is essential. Ensure your insertRule
or addRule
methods provide fallbacks for older browsers.
Security implications
When injecting styles with JavaScript, be wary of CSS Injection attacks. Treat user-supplied data with caution and sanitize it before adding styles.
Performance pointers
For frequent style changes, consider the performance. Minimize direct DOM manipulation to avoid high reflow and repaint costs.
Was this article helpful?