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.
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!