Published on

JS 단원 03: DOM vs HTML 구조 및 document 객체 접근

1. HTML과 DOM의 차이

1-1. HTML은 정적 마크업 언어

<!DOCTYPE html>
<html>
  <head><title>Document</title></head>
  <body><h1>Hello</h1></body>
</html>
  • 브라우저가 읽는 문서
  • 개발자가 작성하는 구조

1-2. DOM은 메모리 상의 트리 구조

  • HTML을 브라우저가 파싱하여 만든 JavaScript 객체 구조
  • 웹 페이지를 자바스크립트로 동적으로 조작할 수 있게 함

2. document 객체란?

브라우저는 window 객체를 전역으로 제공하며, 그 안에 document 객체가 존재합니다.

console.log(document);
  • document는 현재 로드된 웹 페이지 전체를 나타냄
  • HTML 요소에 접근하거나 조작하는 API 제공

3. DOM 요소 접근 방법

3-1. getElementById

const el = document.getElementById("title");

3-2. querySelector / querySelectorAll

document.querySelector(".item");
document.querySelectorAll("ul li");

3-3. getElementsByClassName, getElementsByTagName

  • 실시간 컬렉션을 반환
  • 오래된 API지만 여전히 사용 가능

4. 노드 탐색

const el = document.querySelector("#menu");
el.children;       // 자식 요소
el.parentElement;  // 부모 요소
el.nextElementSibling; // 다음 형제 요소

5. DOM 조작

5-1. 내용 변경

el.textContent = "변경됨";
el.innerHTML = "<strong>굵게</strong>";

5-2. 속성 변경

el.setAttribute("href", "https://example.com");
el.id = "new-id";

5-3. 클래스 조작

el.classList.add("active");
el.classList.remove("active");
el.classList.toggle("dark");

6. 요소 생성과 삽입

const newDiv = document.createElement("div");
newDiv.textContent = "새 요소";

document.body.appendChild(newDiv);

또는 특정 위치에 삽입:

const list = document.querySelector("ul");
const item = document.createElement("li");
item.textContent = "새 항목";

list.insertBefore(item, list.firstChild);

7. 이벤트 연결

const button = document.querySelector("button");

button.addEventListener("click", function () {
  alert("클릭됨");
});

8. DOMContentLoaded vs load

document.addEventListener("DOMContentLoaded", () => {
  // DOM 구조만 완성되면 실행
});

window.addEventListener("load", () => {
  // 이미지, 폰트 등 리소스까지 로드 후 실행
});
  • 스크립트를 <head>에 둘 경우 DOMContentLoaded 이벤트를 활용하면 안전

9. 정리 비교

개념설명
HTML정적인 문서 구조
DOM동적으로 조작 가능한 객체 구조
documentDOM 전체에 접근 가능한 객체
DOM APIgetElementById, querySelector 등
이벤트DOM 조작과 상호작용 구현의 핵심

요약

  • HTML은 마크업, DOM은 메모리 구조이며 자바스크립트로 조작 가능
  • document 객체를 통해 페이지의 구조에 접근 가능
  • querySelector 등의 API로 요소 탐색, 생성, 수정 가능
  • 이벤트와 함께 동적 인터페이스 구현 가능

심화학습

Q1. innerHTML과 textContent의 차이점은?
A1. innerHTML은 HTML 태그 포함 내용을 변경하고, textContent는 순수 텍스트만 변경합니다.


Q2. getElementsByClassName과 querySelectorAll의 차이는?
A2. getElementsByClassName은 실시간 컬렉션을 반환하고, querySelectorAll은 정적 NodeList를 반환합니다.


Q3. DOMContentLoaded와 load 이벤트의 차이점은?
A3. DOMContentLoaded는 HTML 구조만 파싱되면 실행되고, load는 모든 외부 리소스(이미지 등)가 로딩된 후 실행됩니다.