[JS] DOM 개념과 조작방법 (HTMLCollection과 NodeList 차이점까지)

MOONJUNG·2022년 8월 22일
0

JavaScript

목록 보기
2/5
post-thumbnail

DOM이란?

Document Object Model의 약자로
웹페이지의 HTML을 계층화시켜 트리구조로 만든 객체 모델이다

브라우저 → HTML 파일 읽는다 → DOM Tree 구조의 형태로 변환

브라우저는 HTML파일에서 태그들을 브라우저가 이해할 수 있는 자신들만의 오브젝트로 변환한다. 브라우저도 일종의 어플리케이션이기 때문에, 이 어플리케이션은 자신이 이해할 수 있는 오브젝트의 형태로 메모리에 저장한다고 생각하면 쉽다.

HTML ←→ DOM ←→ JavaScript

이로써 자바스크립트는 DOM을 통해 웹페이지에 접근하고, 페이지를 수정할 수 있게 된 것이다.

모든 오브젝트는 이벤트가 발생할 수 있다

  • Node(오브젝트)는 EventTarget을 상속한다.
  • HTML의 모든 태그는 Node(오브젝트)를 상속한다
  • 예를들면
    HTMLDivElement → HTMLElement → Element → Node → EventTarget

DOM 조작 방법

// 아이디(id)
const getId = document.getElementById('getId');
const idName = document.querySelector('#idName');

// 클래스(class)
const getClass = document.getElementsByClassName('getClass');
const className = document.querySelector('.className ');

// 태그 이름(tag name)
document.getElementsByTagName('tag-name');

// 태그 전부(tag all)
const tagAll = document.querySelectorAll('.tagAll ');

JS에서 HTML 추가, 삭제하는 방법

1. 추가 : createElement

const h1 = document.createElement('h1');

2. 태그 속성값 : setAttribute

// 태그 속성값 추가
// Element.setAttribute(key,value);
h1.setAttribute('class','title'); // <h1 class="title"></h1>

// 태그 안에 text 추가
h1.textContent = 'This is a h1 tag'// <h1 class="title">This is a h1 tag</h1>

3. 자식 추가 : appendChild

  • 새로운 자식을 추가할 때

  • 단 부모 안에서 제일 끝부분에 추가

    1. (최신) append
      • string 추가, return되는 value 값이 없음
      • 인터넷 익스플로어 지원X
    2. appendChild
      • 새로 추가된 자식 노드 자체를 return
// 부모요소 = div
const div = document.querySelector('div');	
// 자식요소 = h1
div.appendChild(h1);

4. 특정 위치 추가 : insertBefore

  • 원하는 특정한 부위에 요소를 동적으로 추가
  • 노드를 어떤 reference 노드 전에 추가
// let insertedNode = parentNode.insertBefore(newNode,referenceNode)
div.insertBefore(h1,h3);

5. 삭제 : removeChild

const h1 = document.removeChild('h1');

HTMLCollection과 NodeList 차이점

  • 공통점
  1. DOM API가 여러 개의 결과값을 반환하는 DOM 컬렉션 객체이다.
  2. 배열은 아니지만 유사 배열 객체이기 때문에 이터러블한 성질을 가지고 있다.
  3. Array.from 메서드를 사용하여 배열로 변환 후 사용하기를 권장한다.
  • 차이점
    • HTMLCollection
      • 태그 : getElementsByTagName,getElementsByClassName
      • 프로퍼티 : HTMLCollection.length
      • 메서드 : HTMLCollection.item(), HTMLCollection.namedItem()
      • live 객체 : 노드 객체의 상태 변화를 실시간으로 반영O
      • forEach 함수 사용 불가
    • NodeList
      • 태그 : querySelectorAll
      • 프로퍼티 : NodeList.length
      • 메서드 : NodeList.item(), NodeList.entries(), NodeList.forEach(), NodeList.keys(), NodeList.values()
      • 대부분 Non-live 객체 : 노드 객체의 상태 변화를 실시간으로 반영X, 과거의 정적 상태를 유지
      • childNodes 프로퍼티는 live 객체
      • forEach 사용 가능
profile
뜨거운 열정으로 꿈을 실현하는 프론트엔드 개발자 장문정

0개의 댓글