Frontend/JavaScript

JavaScript DOM

개발자의 첫 걸음 2025. 11. 18. 10:00

안녕하세요. 오늘은 자바스크립트 DOM(Document Object Model)에 대해 알아볼게요.

 

 

 

DOM(Document Object Model)

 

HTML 문서는 브라우저가 읽을 때 트리 구조(계층 구조)로 변환돼요.

 

이때 HTML의 각 요소(div, h1, p 등)문서 객체(Document Object)로 만들어

 

JS가 접근, 수정, 추가, 삭제할 수 있게 해주는 것이 DOM이에요.

 

<body>
  <h1>안녕</h1>
  <p>DOM 배우는 중이에요!</p>
</body>

document
 └── body
      ├── h1
      └── p

그래서 JS는 document.bodydocument.querySelector() 같은 걸로 이 요소들을 불러오고 조작할 수 있어요.

 

 

 

DOM 조작 기본 순서

 

1. DOMContentLoaded 이벤트

 

HTML 구조가 완전히 로드된 다음에 JS 코드가 실행되도록 보장하는 이벤트예요.

document.addEventListener('DOMContentLoaded', () => {
  console.log('문서가 모두 로드되었습니다!');
});

 

 

2. 문서 객체 가져오기 (요소 선택)

 

HTML 요소를 가져오는 대표적인 방법은 다음과 같아요.

메서드 설명 예시
document.querySelector('선택자') 선택자에 맞는 첫 번째 요소 document.querySelector('h1')
document.querySelectorAll('선택자') 선택자에 맞는 모든 요소(배열형) document.querySelectorAll('li')
document.getElementById('id명') 특정 ID를 가진 요소 document.getElementById('main')
HTML
<ul>
  <li>사과</li>
  <li>바나나</li>
  <li>포도</li>
</ul>

JS
document.addEventListener('DOMContentLoaded', () => {
  const items = document.querySelectorAll('li');

  items.forEach(item => {
    item.style.color = 'tomato';
    item.textContent = '리스트 아이템 수정됨!';
  });
});

 

 

3. 문서 객체의 내용 조작

속성 설명 차이점
textContent 텍스트 그대로 출력 HTML 태그 무시
innerHTML HTML 구조로 해석 태그 적용됨
HTML
<div id="a"></div>
<div id="b"></div>

JS
document.addEventListener('DOMContentLoaded', () => {
  const a = document.getElementById('a');
  const b = document.getElementById('b');

  a.textContent = '<h2>이건 그냥 텍스트</h2>'; // 그대로 표시됨
  b.innerHTML = '<h2>이건 실제 제목처럼 보임!</h2>'; // 태그 적용됨
});

 

 

4. 속성(Attribute) 조작하기

메서드 설명
setAttribute('속성명', '값') 속성 추가/변경
getAttribute('속성명') 속성 값 가져오기
HTML
<img class="dog">
<img class="dog">
<img class="dog">

JS
document.addEventListener('DOMContentLoaded', () => {
  const dogs = document.querySelectorAll('.dog');

  dogs.forEach((dog, i) => {
    dog.setAttribute('src', './dog.png');
    dog.setAttribute('alt', `강아지${i + 1}`);
    dog.style.width = (i + 1) * 100 + 'px';
  });
});

 

 

5. 스타일 조작

 

JS에서 CSS 속성을 바꿀 때는 요소.style.속성명 으로 접근해요.

 

CSS의 하이픈(-)카멜표기법으로 바꿔 써야 해요.

CSS 속성 JS에서의 이름
background-color backgroundColor
font-size fontSize
text-align textAlign
const box = document.querySelector('#box');
box.style.backgroundColor = 'blue';
box.style.color = 'white';
box.style.padding = '20px';

 

 

6. 새로운 요소 생성 & 추가

 

생성은 document.createElement('태그명') , 추가는 부모.appendChild(자식)으로 사용해요.

document.addEventListener('DOMContentLoaded', () => {
  const header = document.createElement('h1');
  header.textContent = '동적으로 추가된 제목!';
  header.style.color = 'white';
  header.style.backgroundColor = 'black';

  document.body.appendChild(header);
});

 

 

7. 요소 이동

 

하나의 요소는 항상 하나의 부모만 가질 수 있어요.

 

appendChild()를 다른 부모에 쓰면 기존 위치에서 이동돼요.

HTML
<div id="first"></div>
<div id="second"></div>

JS
const divA = document.getElementById('first');
const divB = document.getElementById('second');
const h2 = document.createElement('h2');
h2.textContent = '이동하는 제목';

function moveToA() {
  divA.appendChild(h2);
  setTimeout(moveToB, 2000);
}

function moveToB() {
  divB.appendChild(h2);
  setTimeout(moveToA, 2000);
}

moveToA();

👉 2초마다 h2가 두 div 사이를 왔다 갔다 함!

 

 

8. 요소 제거하기

 

요소 제거는 부모요소.removeChild(자식요소)를 사용해요.

HTML
<div>
  <h3>곧 사라질 제목</h3>
</div>

JS
document.addEventListener('DOMContentLoaded', () => {
  setTimeout(() => {
    const h3 = document.querySelector('h3');
    h3.parentNode.removeChild(h3); // 부모에서 삭제
  }, 3000);
});

👉 3초 후 h3 요소가 사라집니다.

 

 

 

마지막으로 DOM에 대한 요약정리표예요.

 

기능 메서드 / 속성 설명
문서 로드 후 실행 DOMContentLoaded HTML 구조가 모두 불러진 후 실행
요소 선택 querySelector, getElementById HTML 요소 가져오기
내용 조작 textContent, innerHTML 텍스트 or HTML 구조 삽입
속성 조작 setAttribute, getAttribute 이미지, 링크 등 속성 변경
스타일 변경 요소.style.속성명 CSS 속성 변경
요소 생성 createElement 새 HTML 태그 만들기
요소 추가 appendChild 부모 요소에 추가
요소 삭제 removeChild 부모 요소에서 삭제

 

 

 

여기까지 자바스크립트 DOM에 대해 알아봤는데요.

 

DOM을 잘 활용한다면 HTML을 리모컨 같이 자유롭게 조잘 할 수 있을 것 같아요.

'Frontend > JavaScript' 카테고리의 다른 글

JavaScript Asynchronous  (0) 2025.11.16
JavaScript High-Order Function & Callback Function  (3) 2025.11.15
JavaScript Function  (0) 2025.11.14
JavaScript Array  (0) 2025.11.13
JavaScript control(2)  (0) 2025.11.12