<!DOCTYPE html>
<html lang="ko">
    <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>
        
        <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="ko">
    <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');
    });