Files
2nd/10_Wiki/Topic_Programming/Programming & Language/DOM 요소 조작.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

5.8 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-dom-요소-조작 DOM 요소 조작 10_Wiki/Topics verified self
DOM Manipulation
Vanilla JS DOM
Document API
none A 0.9 applied
dom
javascript
web
browser
2026-05-10 pending
language framework
javascript dom

DOM 요소 조작

매 한 줄

"매 Document 의 tree 의 query + mutation 의 web 기본 API". 매 jQuery 의 era 종료, 2026 의 modern DOM (querySelector, classList, dataset, MutationObserver) 의 충분 + framework (React/Solid/Svelte) 의 abstraction 위. 매 vanilla 의 fast path + 매 small widget 의 right tool.

매 핵심

매 Query

  • getElementById(id) — 매 fastest single lookup.
  • querySelector(sel) / querySelectorAll(sel) — CSS selector general.
  • closest(sel) — 매 ancestor traversal.
  • matches(sel) — boolean check.

매 Mutate

  • Create: createElement, cloneNode(true), <template> + content.cloneNode.
  • Insert: append, prepend, before, after, replaceWith.
  • Remove: el.remove().
  • Attribute: setAttribute, dataset.x, classList.add/toggle/remove.
  • Content: textContent (safe) vs innerHTML (XSS risk).

매 Observe

  • MutationObserver — 매 subtree change.
  • IntersectionObserver — viewport visibility.
  • ResizeObserver — element size.

매 응용

  1. Lightweight widget (no framework) — banner, modal, tooltip.
  2. Server-rendered HTML enhancement (Hotwire, Astro islands).
  3. Browser extension content script.

💻 패턴

Element creation (template)

<template id="card-tpl">
  <article class="card">
    <h3 class="title"></h3>
    <p class="body"></p>
  </article>
</template>
function renderCard({ title, body }) {
  const tpl = document.getElementById('card-tpl');
  const node = tpl.content.cloneNode(true);
  node.querySelector('.title').textContent = title;
  node.querySelector('.body').textContent = body;
  return node;
}
document.querySelector('#list').append(renderCard({ title: 'Hi', body: 'World' }));

classList + dataset

const btn = document.querySelector('#toggle');
btn.classList.toggle('active');
btn.dataset.count = (Number(btn.dataset.count ?? 0) + 1).toString();
// HTML: <button id="toggle" data-count="3">

Event delegation

document.addEventListener('click', (e) => {
  const action = e.target.closest('[data-action]');
  if (!action) return;
  switch (action.dataset.action) {
    case 'open': openModal(action.dataset.id); break;
    case 'delete': remove(action.dataset.id); break;
  }
});

Safe insertion (avoid innerHTML)

// 매 X — XSS
container.innerHTML = `<p>${userInput}</p>`;

// 매 O — textContent
const p = document.createElement('p');
p.textContent = userInput;
container.append(p);

// 매 trusted HTML 만 — Sanitizer API (2026 baseline)
container.setHTML(trustedString);   // 의 native sanitize

IntersectionObserver — lazy load

const io = new IntersectionObserver((entries) => {
  for (const e of entries) {
    if (!e.isIntersecting) continue;
    const img = e.target;
    img.src = img.dataset.src;
    io.unobserve(img);
  }
});
document.querySelectorAll('img[data-src]').forEach((img) => io.observe(img));

MutationObserver — react to subtree

const mo = new MutationObserver((muts) => {
  for (const m of muts) {
    for (const n of m.addedNodes) {
      if (n instanceof HTMLAnchorElement) enhanceLink(n);
    }
  }
});
mo.observe(document.body, { childList: true, subtree: true });

Form serialization

const form = document.querySelector('#login');
form.addEventListener('submit', (e) => {
  e.preventDefault();
  const data = Object.fromEntries(new FormData(form));
  fetch('/login', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } });
});

Animation — Web Animations API

el.animate(
  [{ opacity: 0, transform: 'translateY(10px)' }, { opacity: 1, transform: 'none' }],
  { duration: 200, easing: 'ease-out', fill: 'forwards' },
);

Batched DOM updates

const frag = document.createDocumentFragment();
for (const item of items) frag.append(renderRow(item));
list.append(frag);   // 매 single reflow

매 결정 기준

상황 Approach
Static + small interaction Vanilla DOM
100s of components React / Solid / Svelte
Server HTML + enhancement Hotwire / Astro
Lazy load images IntersectionObserver
External widget injection MutationObserver
Animation Web Animations API

기본값: querySelector + classList + textContent + delegation + Observer APIs.

🔗 Graph

  • 부모: DOM
  • 변형: DOM 요소 조작 및 타입 좁히기 · Shadow_DOM
  • 응용: Web_Components · Hotwire
  • Adjacent: IntersectionObserver · MutationObserver

🤖 LLM 활용

언제: vanilla widget scaffold, Observer setup, jQuery → modern migration. 언제 X: 매 framework app — 매 framework primitive 의 사용.

안티패턴

  • innerHTML with user input: 매 XSS — textContent 또는 Sanitizer.
  • Loop append in DOM: 매 N reflows — DocumentFragment 의 사용.
  • No event delegation: 1000 listener 의 memory + perf 비용.
  • document.write: deprecated — 매 stream block.
  • Manual style mutation everywhere: classList toggle + CSS 의 사용.

🧪 검증 / 중복

  • Verified (MDN DOM, Web Animations, Observers, Sanitizer API spec).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — query/mutate/observe patterns + Sanitizer + delegation