image.png

1. DOM(Document Object Model) API 이란?

DOM 은 HTML 문서의 내용을 트리형태로 구조화하여 웹페이지와 프로그래밍 언어를 연결시켜주는 역할을 합니다. 이때 각각의 요소와 속성, 콘텐츠를 표현하는 단위를 **'노드(node)'**라고 합니다.

Untitled

Untitled

아래 코드를 통해 트리를 탐험해 봅시다.

document.head
document.body
document.body.childNodes
document.body.childNodes[1]
document.body.childNodes[1].tagName
document.body.childNodes[1].innerText
document.body.childNodes[1]. //점만 찍어서 얼마나 많은 애트리뷰트가 있는지 확인해보세요.
document.body.childNodes[2]
document.body.childNodes[2].data

<aside> 🧐 API는 Application Programming Interface 입니다. 쉽게 ‘주문서’라고 기억해주시면 됩니다.

</aside>

2. DOM 트리에 접근하기

document 객체를 통해 HTML 문서에 접근이 가능합니다. document는 브라우저가 불러온 웹페이지를 나타내며, DOM 트리의 진입점 역할을 수행합니다.

// (많이 사용) 해당하는 Id를 가진 요소에 접근하기
document.getElementById();

// 해당하는 모든 요소에 접근하기
document.getElementsByTagName();

// 해당하는 클래스를 가진 모든 요소에 접근하기
document.getElementsByClassName();

// (많이 사용) css 선택자로 단일 요소에 접근하기
document.querySelector("selector");

// css 선택자로 여러 요소에 접근하기
document.querySelectorAll("selector");

3. DOM 제어 명령어

3.1 이벤트 삽입

target.addEventListener( type, listener )의 문법 형태를 지닙니다.

<button>HELLO!</button>
// 이벤트의 타입에는 click, mouseover, mouseout, wheel 등 다양한 이벤트를 감지합니다.
// listener 함수의 인수에는 이벤트에 대한 정보가 담겨있습니다.

const myBtn = document.querySelector("button");

myBtn.addEventListener('click', function(){
	console.log("hello world");
})

3.2 클래스 제어