개발자 첫걸음/The WEb Developer BootCamp 2022

Section 24: DOM이란?

프로아마추어 2022. 4. 27. 19:33

1. DOM 개요

  • Document Object Model
  • 웹 페이지를 구성하는 JavaScript 객체
  • JavaScript 객체를 조작하여 html 요소를 다룰 수 있다.

 

2. DOM

  • mark up된 html 요소(모든 속성, 메서드)와 css를 받아들여 JavaScript 객체로 만들어진다. 
  • JavaScript 객체 관계도에서 가장 최상위 객체는 document이다.
  • console.dir(document); 명령어로 JavaScript 객체를 확인 할 수 있다.
  • Document는 하나의 객체이며 많은 하위 객체들과 함께 웹 페이지를 구성한다.

 

3. getElementById

  • html 요소를 id 값으로 선택하여 다루는 메서드

예제 

// html의 id 값으로 객체 다루기
// id 값은 단 하나의 element만 가지기 때문에 반환 값은 element 혹은 null이 된다.
const 변수 = document.getElementById('아이디 값');

 

4-1. getElementsByTagName 

  • html 요소를 태그 이름으로 선택하여 다루는 메서드
  • getElementById와는 다르게 단일 요소가 아닌 html 요소들을 HTMLCollection 형태로 가지고 온다.
  • HTMLCollection은 배열이 아닌 element의 집합이다. 따라서 배열 메서드는 사용할 수 없다.

예제 

// html의 태그 이름으로 HTMLCollection 다루기
// 태그 이름은 유니크한 값이 아니기 때문에 HTMLCollection 객체가 반환된다.
document.getElementsByTagName('태그 이름');

 

4-2. className

예제

// html의 클래스 이름으로 HTMLCollection 다루기
// 클래스 이름은 유니크한 값이 아니기 때문에 HTMLCollection 객체가 반환된다.
document.getElmentsByClassName('클래스 이름');

 

5-1. querySelector

  • 앞서 알아본 메서드보다 비교적 최근의 메서드로 단일 요소를 반환한다.
  • 여러 개의 요소가 해당하더라도 조건에 부합하는 첫번째 요소만을 반환한다.

예제

// 태그 이름이 h1인 첫번째 요소
document.querySelector('h1');

// id가 red인 첫번째 요소
document.querySelector('#red');

// class가 big인 첫번째 요소
document.querySelector('.big');

 

5-2. querySelectorAll

  • querySelector와는 다르게 요소의 집합인 HTMLCollection을 반환한다.

예제

// 태그 이름이 h1인 요소들
document.querySelectorAll('h1');

// id가 red인 요소들
document.querySelectorAll('#red');

// class가 big인 요소들
document.querySelectorAll('.big');

 

6-1. innerHTML

  • innerHTML은 html로 취급되는 text이다.

예제

// 태그 이름이 h1인 첫번째 요소의 html로 인식하는 text를 변경한다.
document.querySelector(h1).innerHTML = '변경할 내용';

 

6-2. textContent

  • textContent는 html 요소의 열린 태그와 닫힌 태그 사이의 텍스트 값(마크업된 그대로의 내용)이다.

예제

// 태그 이름이 h1인 첫번째 요소의 text를 변경한다.
document.querySelector(h1).textContent = '변경할 내용';

 

6-3. innerText

  • innerText는 html 요소의 열린 태그와 닫힌 태그 사이의 text 값이다.
  • 만약, display:none과 같은 경우라면 해당 텍스트는 무시한다. 즉, 현재 보이는 내용에 따라 text값이 달라진다.

예제

// 태그 이름이 h1인 첫번째 요소의 text를 변경한다.
document.querySelector(h1).innerText = '변경할 내용';

 

7. 속성 (Attributes)

  • html 요소들이 가지고 있는 속성 값들은 굉장히 많다.
  • getAttribute 메서드로 html 요소의 속성 값을 확인 할 수 있다.
  • setAttribute 메서드로 html 요소의 속성 값을 변경하거나 추가할 수 있다.

예제

// getAttribute 메서드로 속성 접근하기
// setAttribute 메서드로 속성 변경하기

// html 요소를 가져온다.
const link = document.querySelector('a');

// href 값을 가져온다.
link.getAttribute('href'); 

// hreft 값 변경하기
link.setAttribute('href', 'http://www.newUrl.com');

 

 

8. 스타일 변경하기

  • JavaScript에서는 style객체의 값이 낙타 표기법으로 작성되어 있다.
  • DOM으로 inline-style을 변경하는 것은 비효율적이다. 
  • css 클래스 정의 후 해당 클래스를 요소에 추가하거나 제거하는 것이 훨씬 효율적이다.

예제

// 폰트 색상 바꾸기
document.querySelector('h1').style.color = '색상';

// 폰트 크기 바꾸기
document.querySelector('h1').style.fontSize = 글자 크기;

 

9. ClassList

  • class를 검색, 조작하기 위해 호출하는 객체

예제 1: class 부여하기 - setAttribuet

const h2 = document.querySelector('h2');

// 첫번째 인자 keyword class, 두번째 인자 부여할 class 이름
h2.setAttribuet('class', 'speical');

예제 2: class 부여하기 - classList

const h2 = document.querySelector('h2');

// class 이름으로 special을 부여했다.
h2.classList.add('special'); // class='speical'

// 추가로 class를 추가할 수 있다.
h2.classList.add('add'); // class='special add'

// remove 메서드로 class 이름을 삭제할 수 있다.
h2.classList.add('add'); // class='special'

예제 3: class 부여하기 - toggle

const h2 = document.querySelector('h2');

// 특정 이벤트가 활성화, 비활성화 될 때마다 
// class를 부여하고 삭제하는 행위를 번갈아 진행할 수 있다.
h2.classList.toggle('special');

 

10. 계층 이동

  • html 요소 간의 계층 구조를 따라 탐색하는 것
  • 부모 요소는 단일로 있을 수 밖에 없다. 자식 요소는 다수여도 무방하다.
  • 자식 요소 가져오기- children()
  • 이전 형제 요소나 다음 형제 요소 가져오기 - previousSibling() & nextSibling()

 예제: 부모 요소 가져오기

const firstBold = document.querySelector('b');

// firstBold의 부모 요소 가져오기
firstBold.parentElement; // <p>...</p>

// firstBold의 조부모 요소 가져오기
firstBold.parentElement.parentElement; // <body>...</body>

// firstBold의 최상위 요소 가져오기
firstBold.parentElement.parentElement.parentElement; // <html><body>...</body></html>

 

11. Append & AppendChild

  • html 요소를 특정 요소에 추가하는 메서드
// 요소 만들기
document.createElement('태그명');

예제 1: appendChild로 요소 만들기

const newImg = document.createElement('img');
// 이미지 src 속성 값 부여
newImg.src = '이미지 주소';

// body 태그에 img 요소 추가
document.body.appendChild(newImg);

예제 2: append로 요소 만들기

const p = document.querySelector('p');

// p요소의 마지막 자식으로 둘 이상의 문자열 추가
p.append('문장 추가한당 히히힝','여러 문장을 추가할 수도 있다구!');

예제 3: prepend로 요소 만들기

const newB = document.querySelector('b');

// b요소의 첫 자식으로 문자열 추가
newB.prepend('안녕!');

예제 4: insertAdjacentElement로 요소 만들기

const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');
h2.append('나는 h2다.'); 

// h1요소 뒤에 형제 요소 추가
h1.insertAdjacentElement('afterend', h2);

예제 5: after로 요소 만들기

const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');

// h1요소 뒤에 형제 요소 추가
h1.after로(h2);

 

12. removeChild & remove

  • html 요소를 삭제하는 메서드

예제 1: removeChild로 요소 지우기

// 지울 요소를 변수에 할당한다.
const firstLi = document.querySelector('li');

// 지우려는 요소의 부모를 변수에 할당한다.
const ul = firstLi.parentElement;

// ul로부터 firstLi 요소 삭제
ul.removeChild(firstLi);


예제 2: remove로 요소 지우기

const img = document.querySelector('img');

// remove 메서드를 호출하는 요소 삭제
img.remove();