I'm trying to update CSS custom properties ("CSS variables") through JavaScript. This works:
element.style.setProperty("--foo", "bar");
element.style.setProperty("--bar", "foo");
element.style.setProperty("border", "10px solid hotpink");
But using Object.assign doesn't work. The border gets applied, but not the CSS variables --foo and --bar.
const styles = {}
styles["--foo"] = "bar";
styles["--bar"] = "foo";
styles["border"] = "10px solid hotpink";
Object.assign(element.style, styles);
Anybody know what's wrong here?
element.style["--foo"] = "bar"will not workstyleobject itself contains whitelisted, recognized CSS properties, likeborder. When you are attempting to assign a non-valid CSS property (e.g. CSS custom property), then it will not be set. You need to set it using.setProperty()instead.stylesobject and apply each property using.setProperty