3 ms·
I'm not a fan of this... /* JS */ var styles = getComputedStyle(document.documentElement); var value = String(styles.getPropertyValue('--primary-color')).trim(
by hanniabu 11y ago
I'm not a fan of this...
/* JS */
var styles = getComputedStyle(document.documentElement);
var value = String(styles.getPropertyValue('--primary-color')).trim();
// value = 'red'
Rather than calling '--primary-color', you should really be able to call 'color' which points to the variable and will still return red. Otherwise you'll have to know the name of each variable being used, which is much more difficult than knowing the property.
- masklinn 11y agoThe point of variables is that you can reuse them, and more importantly changing the variable dynamically changes all of its uses. So of course you have to know the name of the variables, they're an API for your CSS.
- spankalee 11y agoVariables are ultimately used somewhere to set a property, with something like color: var(--primary-color); If care about that property, and not the variable, then get it as usual: let value = styles['color']; // 'red'
- TazeTSchnitzel 11y agoWell, you can also get the computed style for 'color'. What ever made you think you couldn't?
- TabAtkins 11y agoThat's exactly what you can do. var() is replaced at computed-value time, so calling gCS().color will return "red" or whatever. If you use an API that gives you the value at an earlier time, like el.style.color (which is "specified value"), you'll see the var().