Files
2nd/10_Wiki/Topic_CSS/CSS_Variables_JavaScript.md
T
koriweb 9609c04755 docs(10_Wiki): W3Schools 위키화 — HTML/CSS/JavaScript(core)
W3Schools 튜토리얼을 P-Reinforce v3.1 포맷으로 위키화(영어 본문, 한/영 섹션 헤더).
- Topic_HTML: 59문서 (튜토리얼+예제, 레퍼런스/메타 제외)
- Topic_CSS: 190문서 (메인 + Advanced/Flexbox/Grid/RWD 전체)
- Topic_JavaScript: 120문서 (코어 언어; Temporal/DOM상세/BOM/WebAPI/AJAX/jQuery/Graphics 등은 후속)
각 폴더 00_INDEX.md(MOC) 포함. 코드 verbatim, 미확인분은 "Not found in source" 표기.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:21:18 +09:00

106 lines
4.9 KiB
Markdown

---
id: css-variables-and-javascript
title: "CSS Variables and JavaScript"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["CSS custom properties JavaScript", "setProperty CSS variable", "getPropertyValue", "change CSS variable with JS", "CSS variables DOM"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.88
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["css", "web", "frontend", "w3schools", "css-variables", "javascript", "dom"]
raw_sources: ["https://www.w3schools.com/css/css3_variables_javascript.asp"]
applied_in: []
github_commit: ""
---
# [[CSS Variables and JavaScript]]
## 🎯 한 줄 통찰 (One-line insight)
Because CSS variables (custom properties) have access to the DOM, JavaScript can read them with `getComputedStyle().getPropertyValue()` and overwrite them at runtime with `element.style.setProperty()`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **DOM access** — CSS variables have access to the DOM, which means you can change them with JavaScript. [S1]
- **Reading a variable** — get the computed styles for an element with `getComputedStyle()`, then read a specific variable with `.getPropertyValue('--name')`. [S1]
- **Setting a variable** — set a variable's value with `element.style.setProperty('--name', 'value')`. [S1]
- **Root target** — the example targets the `:root` element via `document.querySelector(':root')`, so the changed variable affects everything that references it. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Get pattern** — `getComputedStyle(el).getPropertyValue('--var')` returns the current value of a CSS variable. [S1]
- **Set pattern** — `el.style.setProperty('--var', newValue)` reassigns a CSS variable at runtime, live-updating every rule that consumes it via `var()`. [S1]
- **Single source, dynamic** — by mutating one variable on `:root`, JavaScript can re-theme the page without touching individual rules. [S1]
## 📖 세부 내용 (Details)
**Change Variables With JavaScript** [S1]
CSS variables have access to the DOM, which means that you can change them with JavaScript. The page presents an example of a script that displays and changes the `--primary-bg-color` variable from the example used in the previous pages. (The page notes you do not need to be familiar with JavaScript yet, and links to the W3Schools JavaScript Tutorial.) [S1]
The example script: [S1]
```javascript
<script>
// Get the root element
var r = document.querySelector(':root');
// Function for getting a variable value
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --primary-bg-color variable
alert("The value of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}
// Function for setting a variable value
function myFunction_set() {
// Set the value of variable --primary-bg-color to another value (in this case "green")
r.style.setProperty('--primary-bg-color', 'green');
}
</script>
```
**CSS `var()` function reference** [S1]
| Function | Description |
|----------|-------------|
| `var()` | Inserts the value of a CSS variable |
## 🛠️ 적용 사례 (Applied in summary)
The page's own applied example is a getter/setter script pair: `myFunction_get()` alerts the current `--primary-bg-color` value, and `myFunction_set()` reassigns it to `green` on the `:root` element. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Read a CSS variable (language: JavaScript):
```javascript
var r = document.querySelector(':root');
var rs = getComputedStyle(r);
var value = rs.getPropertyValue('--primary-bg-color');
```
Set a CSS variable (language: JavaScript):
```javascript
var r = document.querySelector(':root');
r.style.setProperty('--primary-bg-color', 'green');
```
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.88
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[CSS Tutorial]]
- **관련 개념:** [[CSS Variables]], [[CSS Variables in Media Queries]], [[CSS @property]], [[CSS var Function]]
- **참조 맥락:** Referenced when a page needs to read or mutate CSS custom properties dynamically from JavaScript (e.g. theme switching).
## 📚 출처 (Sources)
- [S1] W3Schools — CSS Variables and JavaScript — https://www.w3schools.com/css/css3_variables_javascript.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "CSS Variables and JavaScript" page (Astra wiki-curation, P-Reinforce v3.1 format).