there is a good example of this on this tutorial
To simplify the tutorial, we could do the following
In the body you could have something like this:
:root {
--main-color: #42b983;
}
body {
background-color: var(--main-color);
}
To access and change the variable in javascript, you could do the following thing:
// Get the root element
const root = document.documentElement;
// Retrieve the current value of a CSS variable
const currentColor = getComputedStyle(root).getPropertyValue('--main-color');
// Update the CSS variable
root.style.setProperty('--main-color', '#ff5733');
I am not thackling the whole javascript interactions here, as it already has been done in the ansers before, I am just showing the code that updates the root color.