Techstacker
Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.

Pages

No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

How to Add Multiple Styles to an Element With Raw JavaScript (no jQuery!)

Oct 17, 20192 min readJavaScriptViews:

Adding multiple styles to an element with raw vanilla JavaScript can feel a bit clunky. The most common approach I’ve seen to style elements with plain JavaScript is to grab your target element, and then add one style at a time:

// Grab target element (here via its class attribute)
const buttonAddToCart = document.querySelector('.button-add-to-cart')

// Add style properties, one at a time
buttonAddToCart.style.backgroundColor = '#82b97e'
buttonAddToCart.style.color = '#fff'
buttonAddToCart.style.padding = '24px'
buttonAddToCart.style.textTransform = 'uppercase'
buttonAddToCart.style.letterSpacing = '0.1em'

It works, but it’s redundant, there’s too much repetition, and you can’t reuse your code. It’s sort of like using an anonymous function instead of a named function.

Instead of doing the above, you can use a style object:

// Create a style object
const buttonPrimary = {
    backgroundColor: '#82b97e',
    color: '#fff',
    padding: '24px',
    textTransform: 'uppercase',
    letterSpacing: '0.1em'
};

// Assign buttonPrimary (style object) to button element
Object.assign(buttonAddToCart.style, buttonPrimary);

Not only is this approach cleaner, but you can also apply this buttonPrimary style object to any button element that needs primary button styles, and avoid writing repetitive code.

Code example of applying the style object to multiple elements

Wait, why would you use JavaScript to style HTML elements instead of CSS?

Sorry, I’m not taking the bait, CSS in JS, or JSS, is a heated topic among the CSS & JS scene, but I have no dog in this fight. I like both approaches. I suggest you use context as the driver behind the decisions that you make.

But I will make a case for when styling with JavaScript can come handy. Let’s say you’re in a situation where you don’t have direct access to the CSS stylesheet that defines the styling on an element. In this situation, being able to style/overwrite existing styles with JavaScript can be the difference between solving your client’s problem fast, or perhaps not solving it that day.

In this type of scenario, the versatility of JavaScript shines through.