Can CSSStyleDeclaration.setProperty() be relied on to validate CSS properties?

Viewed 136

The following seems to be consistent on major browsers:

const stylesheet = document.createElement('style');
document.head.appendChild(stylesheet);

const sheet = document.styleSheets[0];
sheet.addRule('.temp', '{}', 0);
const style = sheet.cssRules[0].style;

console.log(style.color); // ""
style.setProperty("color", "*****");
console.log(style.color); // ""
style.setProperty("color", "red")
console.log(style.color); // "red"

But I'd like to know: can style.setProperty("color", "*****") be relied on to not set the property, or is this just a coincidentally consistent feature on major browsers right now.

1 Answers

If by "relied on" you mean is it specified in a standard than yes it is.

The relevant standard is CSSOM and for setProperty it says

  1. Let component value list be the result of parsing value for property property.
  2. If component value list is null terminate these steps.

and for the parsing of the value it says

  1. Let list be the value returned by invoking parse a list of component values from value.
  2. Match list against the grammar for the property property in the CSS specification.
  3. If the above step failed, return null.
  4. Return list.

So providing "*****" is not in the list of allowed color values, null will be returned

Then for getting style.color, it says

The camel-cased attribute attribute, on getting, must return the result of invoking getPropertyValue() with the argument being the result of running the IDL attribute to CSS property algorithm for camel-cased attribute.

and then for getPropertyValue() it says

  1. If property is a case-sensitive match for a property name of a CSS declaration in the declarations, return the result of invoking serialize a CSS value of that declaration and terminate these steps.

Finally, null values get serialized as the empty string.

Related