165

Is there a way to access a css variable from javascript? Here my css variable declaration.

:root {
  --color-font-general: #336699;
}
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Pablo
  • 2,581
  • 3
  • 16
  • 31
  • 1
    I am really curious as to why you don't want to re-declare that variable in javascript which is more efficient – Trash Can Jan 18 '17 at 17:29
  • 8
    @Dummy Then there would be two places in which the value needed to be maintained, making the code more fragile (i.e. not a DRY approach). – Delon Nov 08 '18 at 10:27
  • 1
    In my case, I don't know which CSS file it's using. The user decides the file, and each file has different values for this variable. – Jaden Baptista Jan 01 '19 at 01:10
  • 3
    Also, if you have CSS variables that have different values depending on which active `@media` query defines them, you save yourself even more work and duplicate code. – Claus Wahlers Jan 08 '19 at 05:00

2 Answers2

290

Just the standard way:

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property
getComputedStyle(element).getPropertyValue('--color-font-general');

Example:

var style = getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }
vsync
  • 118,978
  • 58
  • 307
  • 400
Oriol
  • 274,082
  • 63
  • 437
  • 513
59

Use this:

window.getComputedStyle(document.documentElement).getPropertyValue('--color-font-general');

And you can change it like this:

document.documentElement.style.setProperty('--color-font-general', '#000');

source

Louay Alakkad
  • 7,132
  • 2
  • 22
  • 45