<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Controlling CSS Variables with JavaScript</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="target-element">
            Hello, this is a text with dynamic styles!
        </div>
        
        <button type="button" id="changeStylesBtn">Change Styles</button>
        
        <script src="script.js"></script>
    </body>
</html>
:root {
    --main-color: blue;
    --font-size: 16px;
}
.target-element {
    color: var(--main-color);
    font-size: var(--font-size);
}
// 1. Use window.getComputedStyle() to get the current values of CSS variables.
const rootStyles = window.getComputedStyle(document.documentElement);
const targetElement = document.querySelector(".target-element");

const mainColorValue = rootStyles.getPropertyValue("--main-color");
const fontSizeValue = rootStyles.getPropertyValue("--font-size");

console.log(mainColorValue); // Output: "blue"
console.log(fontSizeValue);  // Output: "16px"

// 2. When the "Change Styles" button is clicked, dynamically update the CSS variables to change styles.
document.getElementById("changeStylesBtn").addEventListener("click", () => {
    // 3. Use element.style.setProperty() to update the CSS variables.
    targetElement.style.setProperty("--main-color", "red");
    targetElement.style.setProperty("--font-size", "20px");
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Control CSS Variables with JavaScript</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="target-element">
            Hello, this is a text with dynamic styles!
        </div>

        <button id="changeStylesBtn">Change Styles</button>

        <!-- Load jQuery library -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="script.js"></script>
    </body>
</html>
:root {
    --main-color: blue;
    --font-size: 16px;
}
.target-element {
    color: var(--main-color);
    font-size: var(--font-size);
}
// 1. Use jQuery to get the current values of CSS variables
const mainColorValue = $(":root").css("--main-color");
const fontSizeValue = $(":root").css("--font-size");

console.log(mainColorValue); // Output: "blue"
console.log(fontSizeValue);  // Output: "16px"

// 2. When the "Change Styles" button is clicked, dynamically update the CSS variables
$("#changeStylesBtn").on("click", () => {
    // 3. Use jQuery to update the CSS variable values
    $(".target-element").css("--main-color", "red");
    $(".target-element").css("--font-size", "20px");
});