Access CSS variable from javascript

JavascriptCssCss Variables

Javascript Problem Overview


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

:root {
  --color-font-general: #336699;
}

Javascript Solutions


Solution 1 - Javascript

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); }

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPabloView Question on Stackoverflow
Solution 1 - JavascriptOriolView Answer on Stackoverflow
Solution 2 - JavascriptLouay AlakkadView Answer on Stackoverflow