getPropertyValue() includes whitespace of CSS formating when retrieving Custom CSS Property Values
When I get the value of a custom CSS property, the getPropertyValue
method returns a DOMString that includes the whitespace I used in my CSS formatting. Is there a different method that I should be using to obtain the value of custom CSS properties (one that doesn’t require trimming afterwards)?
function getCustomPropertyValue(element,customPropertyName) { let style = window.getComputedStyle(element); return style.getPropertyValue(customPropertyName); } let value = getCustomPropertyValue(document.body,"--color1"); console.log(`'${value}'`);
body { --color1: #333333; }
Notice that, when you run the code snippet, the getPropertyValue
function returns a value having a leading whitespace (that is an artifact of my CSS formatting).
It works when you use CSS variables the right way. You can find more details here.
function getCustomPropertyValue(element, customPropertyName) { let style = window.getComputedStyle(element); return style.getPropertyValue(customPropertyName); } let value = getCustomPropertyValue(document.body, "--color1"); console.log(`'${value}'`);
:root { --color1:#333333; } body { color: var(--color1); }