My understanding is there are two equivalent ways to set CSS rules via JavaScript:
#1: element.style.setProperty(propertyName, value)
#2: element.style.propertyName = value
I have always favored the second, shorter method.
When it comes to CSS variables, I find I have to use an explicit setProperty call:
element.style.setProperty('--varName', value)
This approach has no effect on variables:
element.style['--varName'] = value
Why is this?
style
works is very simple in that it overrides all styles from stylesheets (setting aside!important
). Because CSS variables need to consider the scope of the variable, I'm guessing thatsetProperty()
simply does more background work, determining which stylesheet contains the rule that has highest priority, and/or analysing the scope of the given variable. I suppose they could make a default:root
scope, but apparently did not. Again, just a guess.setProperty
.setProperty()
. You can see that it has a step specifically to deal with a "custom property", which is spec'd here, and defined as "any property whose name starts with two dashes". So thesetProperty()
method is specifically designed to deal with CSS vars. I'm guessing thestyle
setter is not spec'd to handle it, but I haven't looked yet.