Explain Codes LogoExplain Codes Logo

How can I set multiple CSS styles in JavaScript?

javascript
prompt-engineering
functions
performance
Nikita BarsukovbyNikita Barsukov·Nov 25, 2024
TLDR

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:

Object.assign(element.style, { backgroundColor: 'blue', // dressing in blue today! color: 'white', // life in monochrome, paint it white! border: '1px solid black' // and a bold border to wrap it up! });

For applying more than one style using a string, take advantage of cssText:

element.style.cssText = "background-color: blue; color: white; border: 1px solid black;";

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:

function applyStyles(element, styles) { Object.assign(element.style, styles); // where styles take flight! } applyStyles(someElement, { // dressing up someElement in fancy styles color: 'red', // red for power! fontSize: '16px', // keeping it readable marginBottom: '10px' // give it some breathing space! });

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:

const styles = { color: 'green', // green, not just for veggies! fontWeight: 'bold' // bold, because why not! }; for (const property in styles) { element.style[property] = styles[property]; // only change specified styles! }

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:

element.style.cssText = ` background-color: ${backgroundColor}; color: ${textColor}; border: ${borderWidth} solid ${borderColor}; `;

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:

const existingStyles = element.style.cssText; element.style.cssText = `${existingStyles}; font-size: 18px;`; // Existing styles remain untouched!

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:

document.querySelector('.my-class').style.cssText += 'display: flex;'; // .my-class is now going flexible, literally!

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.