IT/HTML,CSS,JavaScript

[JavaScript] 자바스크립트 기초 복습 part 12

j8970 2025. 4. 3. 17:18

📌 DOM (Document Object Model)


🔹 DOM이란?

DOM(Document Object Model)이란 웹 페이지를 문서 객체로 조작하고 관리할 수 있는 인터페이스입니다.

문서 객체란?

  • HTML 안에서 요소(Element)로 불리는 객체를 의미합니다.
  • JavaScript에서 문서 객체는 HTML 요소를 의미합니다.

🔹 DOM 사용 방법

JavaScript를 사용하여 HTML 요소를 문서 객체로 선택, 추가, 수정, 삭제할 수 있습니다. 즉, CRUD(Create, Read, Update, Delete) 작업이 가능합니다.


🔹 DOM 조작 방법

1️⃣ DOMContentLoaded 이벤트

HTML 문서가 모두 로드된 후에 실행되는 이벤트입니다.

// 문서가 모두 로드된 후 실행
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM이 완전히 로드됨');
});

2️⃣ 문서 객체 가져오기

📌 1) 전체 HTML 구조를 객체로 가져오기

console.log(document.head);   // <head> 요소
console.log(document.title);  // 문서 제목

📌 2) querySelector() & querySelectorAll() 메서드

  • querySelector() : 선택한 요소 중 첫 번째 요소를 반환
  • querySelectorAll() : 선택한 요소들을 배열로 반환
document.addEventListener('DOMContentLoaded', () => {
  // querySelector()
  const header = document.querySelector('h1');
  header.textContent = 'HEADER ONE';
  header.style.color = 'white';
  header.style.backgroundColor = 'black';
  header.style.padding = '20px';

  // querySelectorAll()
  const items = document.querySelectorAll('li');
  items.forEach(item => {
    item.textContent = 'LIST ITEM';
    item.style.color = 'pink';
    item.style.listStyle = 'none';
    item.style.backgroundColor = 'black';
  });
});

📌 3) getElementById() 메서드

  • getElementById() : 특정 ID를 가진 요소를 반환 (문서 내에서 유일해야 함)
  • getElementsByClassName() : 특정 클래스를 가진 요소들을 컬렉션 객체로 반환
document.addEventListener('DOMContentLoaded', () => {
  const divElement = document.getElementById('getElementByID');
  divElement.style.color = 'blue';
  divElement.style.backgroundColor = 'yellow';
  divElement.classList.add('special');
});

🔹 DOM 조작 기능

1️⃣ 글자 조작하기

  • textContent : 입력된 문자열 그대로 출력
  • innerHTML : HTML 형식으로 문자열을 출력
document.querySelector('h1').textContent = '새로운 제목';
document.querySelector('p').innerHTML = '<strong>강조된 문장</strong>';

2️⃣ 속성 조작하기

  • HTML 요소의 속성을 추가, 변경, 가져올 수 있음
const img = document.querySelector('img');
img.setAttribute('src', 'new-image.jpg'); // 이미지 변경
console.log(img.getAttribute('src'));     // 현재 src 값 출력

3️⃣ 스타일 조작하기

  • style 속성을 활용하여 요소의 CSS 스타일을 변경
const box = document.querySelector('.box');
box.style.width = '200px';
box.style.height = '100px';
box.style.backgroundColor = 'lightblue';

🚀 HTML 요소 조작하기!