드디어 화면이 바뀐다
지금까지 배운 JavaScript는 콘솔에만 출력됐습니다. 이번 편부터는 실제 웹 페이지 화면을 JavaScript로 바꿉니다.
글자를 클릭하면 색이 바뀌고, 버튼을 누르면 새 내용이 나타납니다. 이것이 DOM 조작입니다.
DOM이란?
DOM(Document Object Model) 은 브라우저가 HTML 문서를 읽어들여 만든 트리 구조의 객체 모델입니다.
document
└── html
├── head
│ └── title
└── body
├── h1
├── p
└── div
└── button
JavaScript는 이 트리를 통해 HTML 요소를 찾고, 내용을 바꾸고, 스타일을 변경할 수 있습니다.
요소 선택하기
querySelector — CSS 선택자로 첫 번째 요소 선택
// 태그 선택
const title = document.querySelector("h1");
// 클래스 선택
const card = document.querySelector(".card");
// 아이디 선택
const btn = document.querySelector("#submit-btn");
// 자손 선택
const navLink = document.querySelector("nav a");
querySelectorAll — 모두 선택
// 모든 p 태그를 선택 (NodeList 반환)
const paragraphs = document.querySelectorAll("p");
// 반복 처리
paragraphs.forEach(p => {
console.log(p.textContent);
});
요소 내용 변경
textContent — 텍스트만
const title = document.querySelector("h1");
console.log(title.textContent); // 현재 텍스트 읽기
title.textContent = "새로운 제목!"; // 텍스트 변경
innerHTML — HTML 포함
const container = document.querySelector(".container");
// HTML 태그 포함해서 변경
container.innerHTML = "<p>새로운 <strong>내용</strong>입니다.</p>";
innerHTML은 HTML을 직접 삽입할 수 있지만, 사용자 입력을 그대로 넣으면 보안 위험이 있으므로 주의합니다.
요소 스타일 변경
const box = document.querySelector(".box");
// 스타일 직접 변경 (camelCase 사용)
box.style.backgroundColor = "red";
box.style.fontSize = "24px";
box.style.display = "none"; // 숨기기
box.style.display = "block"; // 다시 보이기
CSS 속성명에서 -를 없애고 다음 글자를 대문자로 씁니다.
background-color→backgroundColorfont-size→fontSizeborder-radius→borderRadius
클래스 조작 — classList
스타일 변경은 클래스 추가/제거로 하는 것이 더 깔끔합니다.
const btn = document.querySelector("button");
// 클래스 추가
btn.classList.add("active");
// 클래스 제거
btn.classList.remove("active");
// 클래스 토글 (있으면 제거, 없으면 추가)
btn.classList.toggle("active");
// 클래스 있는지 확인
btn.classList.contains("active"); // true / false
/* CSS에서 미리 정의 */
.active {
background-color: #0070f3;
color: white;
}
요소 속성 변경
const img = document.querySelector("img");
const link = document.querySelector("a");
// 속성 읽기
console.log(img.getAttribute("src"));
// 속성 변경
img.setAttribute("src", "new-image.jpg");
img.setAttribute("alt", "새 이미지 설명");
link.href = "https://example.com"; // 직접 접근도 가능
실전 예제: 다크 모드 토글
<button id="theme-btn">다크 모드</button>
const btn = document.querySelector("#theme-btn");
btn.addEventListener("click", () => {
document.body.classList.toggle("dark");
if (document.body.classList.contains("dark")) {
btn.textContent = "라이트 모드";
} else {
btn.textContent = "다크 모드";
}
});
body.dark {
background-color: #1a1a2e;
color: #f0f0f0;
}
새 요소 만들기
// 1. 요소 생성
const newItem = document.createElement("li");
newItem.textContent = "새 항목";
newItem.classList.add("item");
// 2. 기존 요소에 추가
const list = document.querySelector("ul");
list.appendChild(newItem); // 마지막에 추가
list.prepend(newItem); // 처음에 추가
직접 해보기 ✏️
<h1 id="title">안녕하세요</h1>
<button id="change-btn">제목 바꾸기</button>
<button id="toggle-btn">색상 토글</button>
목표:
#change-btn클릭 시#title텍스트를 "반갑습니다!"로 바꾸기#toggle-btn클릭 시#title색상을 파란색 ↔ 빨간색으로 토글
// 힌트
const title = document.querySelector("#title");
const changeBtn = document.querySelector("#change-btn");
changeBtn.addEventListener("click", () => {
title.textContent = "반갑습니다!";
});
정리
| 기능 | 코드 |
|---|---|
| 요소 선택 | document.querySelector(".클래스") |
| 모두 선택 | document.querySelectorAll("태그") |
| 텍스트 변경 | element.textContent = "..." |
| HTML 변경 | element.innerHTML = "..." |
| 스타일 변경 | element.style.color = "red" |
| 클래스 토글 | element.classList.toggle("이름") |
| 요소 생성 | document.createElement("태그") |
다음 편에서는 이벤트 처리 — 클릭, 입력, 스크롤 등 사용자 행동에 반응하는 방법을 배웁니다.