2

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?

4
  • 1
    to reduce the problem, even element.style["--foo"] = "bar" will not work Commented Nov 26, 2019 at 9:36
  • I suppose the reason why is because the style object itself contains whitelisted, recognized CSS properties, like border. 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. Commented Nov 26, 2019 at 9:39
  • Go through this MDN web docs - HTMLElement.style Commented Nov 26, 2019 at 9:54
  • 1
    Here's a way to do this: jsfiddle.net/khrismuc/8kqap1dn (the key is to iterate over the styles object and apply each property using .setProperty Commented Nov 26, 2019 at 11:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The need to use setProperty() for custom properties is the same on any CSSStyleDeclaration object, regardless of whether it's from element.style or in any other part of the CSSOM. The issue is, as you say up front, that CSS property declarations are not simple JS object properties, they need getters/setters to have an effect & only recognized CSS properties have them defined, as spec'd in these CSSOM partial interfaces.
style["background-image"] = ... does work, actually, and is specified in CSSOM as "dashed attribute".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.