3

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

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • 1
    if you write your css like this `body { --color1:#333333; }` then its gone. kinda funny. i would trim your return value – bill.gates Jul 06 '20 at 06:25
  • I noticed that too and do intend to trim if `getPropertyValue` is indeed the proper way to acquire custom CSS property values. – Lonnie Best Jul 06 '20 at 06:27

3 Answers3

4

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.

Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
1

Just remove white-space in the CSS.

body { 
--color1:#333333; 
}
John Din
  • 53
  • 1
  • 6
0

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);
}
Gerard
  • 15,418
  • 5
  • 30
  • 52
  • When I run your code snippet, I see the [vary same leading space](https://i.stack.imgur.com/TyM6Q.png) that's outputted by mine. Getting the value from a descendant element, instead of the one where the custom value was created is not something I'd call "the right way". I can think of circumstances where the value can be different based on the element you ask and the right way is completely circumstantial. – Lonnie Best Jul 06 '20 at 14:34
  • 1
    @LonnieBest and the leading space is gone. Almost like a card trick. – Gerard Jul 06 '20 at 15:17
  • 1
    You cheated! You changed `--color1: #333333;` to `--color1:#333333;` (removing that space from the CSS itself). You can't trick a [card trick programmer](http://www.lonniebest.com/CardTrick/), buddy! It's all good though. Enjoyed it. I up-voted you anyway. – Lonnie Best Jul 07 '20 at 07:06
  • auto formatters like prettier always adds this space – MAZ Dec 23 '22 at 08:49