How to assign and apply a JSON object with CSS styles to an element in JavaScript

The most current version as of .

Say you have selected an element via JavaScript:

const someElement = document.querySelector(".some-elements-class");

And you have an object of given CSS styles in your JavaScript code:

const someElementNewStyles = {
  background: "red",
  color: "white",
  // …
};

And now you want to assign all these new styles to the selected element.

What you could do is:

someElement.style.background = "red";
someElement.style.color = "white";
// …

But that sucks, you do not want to repeat yourself every single time. Also, this method is not that flexibel, as you can only assign one CSS property with one declaration.

So, instead of the above method, what you can do is using Object.assign():

Obejct.assign(someElement.style, someElementNewStyles);

Here you assign all the new CSS styles of the someElementNewStyles object to the elements style property.

Voilà - that’s it.

For more details on the Object.assign() method make sure to check out the docs at MDN.

— David Wolf