Reputation: 11374
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).
Upvotes: 4
Views: 1729
Reputation: 19349
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.
Upvotes: 5
Reputation: 15786
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);
}
Upvotes: 0