javascriptcssdomcustom-properties

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).


Solution

  • This is a deliberate decision to allow custom CSS properties to consider whitespace significant. So trimming is the way to go.

    I have heard that registering the property with a defined syntax may change that, but I don't think it's standard yet nor have I tried it myself.