RoelN
RoelN

Reputation: 2321

Set CSS custom properties through Object.assign

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?

Upvotes: 2

Views: 1090

Answers (1)

Note that the element.style object is a convenience object for mapping styles, but it's not the "real CSS".

As per Amelia's comment, all spec-defined css properties have predefined getters/setters on the style object, but this is (necessarily) not the case for custom properties. As such, the only way to properly trigger what needs to happen is through the getProperty/setProperty mechanism.

Upvotes: 1

Related Questions