'Access CSS variable from javascript [duplicate]
Is there a way to access a css variable from javascript? Here my css variable declaration.
:root {
--color-font-general: #336699;
}
Solution 1:[1]
Just the standard way:
- Get the computed styles with
getComputedStyle
- 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:[2]
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');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vsync |
Solution 2 |