Using Object.assign() to quickly set multiple inline styles

Since an HTMLElement its CSSStyleDeclaration (viz. its style property) essentially is an Object, it’s perfectly possible to pass it as the target object into Object.assign() along with a few other objects.

The result is that all keys from those extra objects will be merged as CSS properties along with their values on the currently applied styles. A lot faster than applying them one-by-one (*).

const $demo = document.querySelector('#demo');

Object.assign(demo.style, {
    display: 'inline-block',
    padding: '0.2em 0.4em',
    borderRadius: '0.4em',
    color: 'white',
    fontWeight: 700,
    background: 'rebeccapurple',
});

Here’s a demo pen:

(*) I know, a better approach would be to assign just one extra className onto an HTMLElement in order to apply a set of CSS rules onto it. I’m merely pointing out here that it’s possible to do this kind of thing.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.