<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>JavaScriptでCSS変数を操作する</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. CSS変数の現在の値を取得するために、window.getComputedStyle() 関数を使用します。
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); // 出力結果: "blue"
console.log(fontSizeValue); // 出力結果: "16px"

// 2. 「Change Styles」ボタンがクリックされたときに、CSS変数の値を変更してスタイルを動的に操作します。
document.getElementById('changeStylesBtn').addEventListener('click', () => {
    // 3. CSS変数の値を変更するために、element.style.setProperty() 関数を使用します。
    targetElement.style.setProperty('--main-color', 'red');
    targetElement.style.setProperty('--font-size', '20px');
});
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>JavaScriptでCSS変数を操作する</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>
        
        <!-- jQueryライブラリを読み込みます。 -->
        <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. CSS変数の現在の値を取得するために、window.getComputedStyle()の代わりにjQueryを使用します。
const mainColorValue = $(':root').css('--main-color');
const fontSizeValue = $(':root').css('--font-size');

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

// 2. 「Change Styles」ボタンをクリックすると、CSS変数の値を変更してスタイルを動的に操作します。
$('#changeStylesBtn').on('click', () => {
    // 3. CSS変数の値を変更するためにjQueryを使用します。
    $('.target-element').css('--main-color', 'red');
    $('.target-element').css('--font-size', '20px');
});