'Setting CSS styles with destructured JS object

I am trying to create an object with the styles that I need and then set them to my element simply by destructuring and combining the objects, but for whatever reason it is not working:

const styles = { color: "#FFFFFF" }

const element = document.querySelector(".someElementSelector");

element.style = { ...element.style, ...styles };

However the styles just get set to empty strings, I know that because if I do:

const styles = { color: "#FFFFFF" }

const element = document.querySelector(".someElementSelector");

element.style.color = "#FFFFFF";

element.style = { ...element.style, ...styles };

color is an empty string "", but if I remove the last line with destructuring entirely, the color is being set correctly.



Solution 1:[1]

HTMLElement.style is a read-only object. If you assign a string it automatically instead is assigned to its property cssText.

You can destructure using Object.entries(styles):

const styles = {
  color: "red",
  fontSize: "30px",
  textDecoration: "underline",
  transform: "rotate(45deg)",
  transformOrigin: "top left"
}

for (const [prop, value] of Object.entries(styles)) {
  el.style[prop] = value;
}
<div id="el">ABC</div>

You can also use Object.assign() (which basically is a shortcut to the first example):

const styles = {
  color: "red",
  fontSize: "30px",
  textDecoration: "underline",
  transform: "rotate(45deg)",
  transformOrigin: "top left"
}

Object.assign(el.style, styles);
<div id="el">ABC</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1